grep beginning of file?
In a linux shell, I want to make sure that a certain set of files all begin with <?
, having that exact string and no other characters at the beginning. How can I grep or use some other to express "file begins with"?
Edit: I'm wildcarding this, and head
doesn't give a filename on the same line, so when I grep it, I don't see the filname. Also, "^<?"
doesn't seem to give the right results; basically I'm getting this:
$> head -1 * | grep "^<?"
<?
<?
<?
<?
<?
...
All of the files are actually good.
In Bash:
for file in *; do [[ "$(head -1 "$file")" =~ ^\<\? ]] || echo "$file"; done
Make sure they are files:
for file in *; do [ -f "$file" ] || continue; [[ "$(head -1 "$file")" =~ ^\<\? ]] || echo "$file"; done
Do the grep
:
$ head -n 1 * | grep -B1 "^<?"
==> foo <==
<?
--
==> bar <==
<?
--
==> baz <==
<?
Parse out the filenames:
$ head -n 1 * | grep -B1 "^<?" | sed -n 's/^==> \(.*\) <==$/\1/p'
foo
bar
baz