Reputation: 69
I would like to know how can a grep for a specific field on each line of a file. I don't want to grep the entire line for a pattern.
e.g.
33 >> sender1 >> recipient2 >> subject vvv
33 >> sender2 >> recipient2 >> subject aaa
22 >> sender1 >> recipient3 >> subject ccc
22 >> sender1 >> recipient3 >> subject xxx
Thank You!
Upvotes: 1
Views: 106
Reputation: 302
awk is sweet, but the following might be more intuitive for a non awk user.
recipient field:
cut -d'>' -f5 filename | grep searchString
sender and recipient field:
cut -d'>' -f3,5 filename | grep searchString
But you do lose the rest of the line.
Upvotes: 0
Reputation: 4841
A variation on what has been posted already:
awk -F' *>> *' '$3=="recipient2"'
This sets the Field Separator to something more useful, as it includes the spaces. And now recipient20
will not be matched. You could prevent these false matches by including anchors like ^
and "$, or
>and
\<``, but testing for equality is often easier.
The following has tests for the second field, in the first variant the line is printed if any of the two match, in the second, when both conditions are met:
awk -F' *>> *' '$3=="recipient2" || $2=="sender1"'
awk -F' *>> *' '$3=="recipient2" && $2=="sender1"'
Upvotes: 0
Reputation: 195209
"grep" on recipient only:
awk -F'>>' '$3~/yourPattern/' file
on recipient and sender:
awk -F'>>' '$3~/yourPattern/||$2~/yourPattern/' file
Upvotes: 5
Reputation: 104
Use awk
instead of grep
, for searching in sender filed
$ awk '$3 ~ /sender/ { print }' filename.txt
For searching in sender and recipient filed
$ awk '$3 ~ /sender2/ || $5 ~ /recipient2/ { print }' filename.txt
Fields are separated by white space. You can add your custom delimiter by awk -F">>" '$3 ~ /sender/ { print }' filename.txt
You can use conditions in AND,OR
by replacing || for OR
and && for AND
logic.
Upvotes: 4