Seeking help with search

Hello All,

I'm looking for some help with grepping for two specific strings in files with multiple lines. For instance, I have files and the content looks like this:

=====Start=====
Record:1
        Field 1 = aaaaaaaaaa
        Field 2 = bbbbbbbbbb
        Field 3 = 1234567890
        Field 4 = 0000000123
        Field 5 = ccccccccccc
=====End=======

I would like to search through the file looking for 1234567890. I can easily grep on that but I also need the value of field 4 (and I don't know the value of field 4) and I need to out put this to a text file. Essentially the output text file should contain only:

        Field 3 = 1234567890
        Field 4 = 0000000123

How do I search for this?

for file in *
 do
 grep 1234567890
 ?????
 done > results.txt

Unless there are LOTS of files, try:

grep -F -e 1234567890 -e "Field 4" * > results.txt
1 Like

Thanks for the response.

I was just looking at the contents of the files further and looks as though I'll need something a little different. It appears as though 1234567890 can appear in field 3 or field 4. :mad:

So I'm thinking perhaps an "IF" statement? Something like...

if Field3=1234567890
 then print Field3 and Field4
else if field4=1234567890
 then print Field3 and Field4
fi

awk somewhat resembles grep on steroids, it scans lines but is a proper language with variables and columns and things.

awk '($3 == V) || ($4 == V) { print $3,$4 }' V=1234567890 inputfile

Try:

sed -n '/Field 3/{N;/1234567890/p;}' file*
1 Like

I must be doing it wrong. It's not returning a value. A simple grep echos the 1234567890 value so I know it's in there, but the awk statement is not finding it.

$3 and $4 are representations of Fields 3 and 4 correct?

---------- Post updated at 10:02 PM ---------- Previous update was at 09:49 PM ----------

This appeared to have worked for what I want

grep -B 1 -A 1 "1234567890" *.txt

I didn't know grep had a B (before) and A (after) option that allows you to print the line before and the line after the search string.

Yes but that is equivalent to (GNU) grep -C 1 and it will show 3 lines per match instead of two..

This worked as well.

Thanks.

---------- Post updated at 11:31 PM ---------- Previous update was at 11:25 PM ----------

You're right. But since the search string appeared in both Field 3 and 4, I needed to pull both before and after lines. I could've used the command below to get just the two files i needed:

grep -B 1 1234567890 file

Only when 1234567890 occurs in field 4, not when it occurs in field 3

Correct.