Young Fu
Young Fu

Reputation: 1287

grep for files containin specific text in a specific line at a specific position

I need to grep for filenames of files that have certain string ("OB") in a certain position (7-8) of a certain line (line 1) of the file.

What is the best way to do that.

Upvotes: 3

Views: 450

Answers (3)

twalberg
twalberg

Reputation: 62379

awk might be better for this job:

line=1
pos=7
len=2
awk "FNR==${line} && substr(\$0,${pos},${len})=='OB'{print FILENAME}" myfiles

Or alternatively:

awk -vl=${line} -vp=${pos} -vn=${len} 'FNR==l && substr($0,p,n)=="OB"{print FILENAME}' myfiles

Upvotes: 0

hwnd
hwnd

Reputation: 70732

What about using awk..

awk 'FNR == 1 && /^.{6}OB/ {print FILENAME; nextfile}' *

Upvotes: 2

zb226
zb226

Reputation: 10500

How about using head to get the first line of each file, then grep with a corresponding regexp and output the line before to retain the filename:

head -n1 * | grep -EB1 '^.{6}OB'

Of course, you have to change the file selection - here *- to suit your needs.

Update: Question was updated - If you just want the filenames, just add another grep to catch the filenames given by the head command:

head -n1 * | grep -EB1 '^.{6}OB' | grep '==>'

Upvotes: 2

Related Questions