Grep for first word of first line in files?

Hork

Senior member
Mar 8, 2000
531
0
0
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?
 

tranceport

Diamond Member
Aug 8, 2000
4,168
1
81
www.thesystemsengineer.com
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.
 

QED

Diamond Member
Dec 16, 2005
3,428
3
0
Or, you can use this code (all on one line) which prints just the filenames:


 

Armitage

Banned
Feb 23, 2001
8,086
0
0
head -n1 * | egrep -B1 ^WORDTOBEFOUND

Output is a little messy, but it's there.

Or in python...
 

drag

Elite Member
Jul 4, 2002
8,708
0
0
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