• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Grep for first word of first line in files?

Hork

Senior member
Anyone familiar with regular expressions that can tell me how to grep for the first word of the first line of a set of files?

I have a bunch of csv files, and I would like to get the filenames of the files that have a certain value as the first word of the first line of the file.

I know I can use ^wordiamseachingfor to get the word at the start of the line, but how can I limit the search to the first line of the file?
 
Depending on your word seperator in the file.

try head -n 1 <filename> | awk -F" " '{ print $1 }'

Where <filename> is the file you are working with.
You can change " " to "," if it is comma seperated etc.

You may take a look at xargs if you have a lot of files to do this to.

This will give you the first word of each file. Build a new file with this first word and also the filename.

Now grep for just that word you want and it will show lines with filenames.

You can pretty the process up from here.
 
Use the 'head' command.

I am sure your familar with the 'tail' command which you can use to output the last few lines of a file or you can use -f to follow the output of a new file.. Well 'head' is the oppisite. It outputs the first line.

head -n 1 filename

or
cat filename |head -n 1

or
find|while read i; do if [ `head -n 1 "$i"` == "string" ]; then echo "$i";fi;done

Or something like that.
You get the idea.

edit:
or
find|while read i; do if head -n1 "$i"|grep "string"; then echo "$i";fi;done > filelist

edit2:
oops forgot to silence the grep.
find|while read i; do if head -n1 "$i"|grep "string" > /dev/null; then echo "$i";fi;done > filelist
 
Back
Top