Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Printing lines with same value of a certain field 1

Status
Not open for further replies.

zbabic

Technical User
Jun 9, 2007
3
CH
Hello to everyone. I need a help with this one.
I have a multicolumn file and I want to get a new file which contains only those lines that have the same value of a certain field (say 3rd) - all of them.

For example, I want this:

1 2 3 p
w 3 5 l
q 9 3 i
w 1 3 m
1 z 1 e
2 d 5 v
t 1 2 7

to become this:

1 2 3 p
w 3 5 l
q 9 3 i
w 1 3 m
2 d 5 v

Thank you.

Zeljko Babic
 
And what have you tried so far and where in your code are you stuck ?

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Well, for the record, I'm new to awk so lpease be patient with me. :)
I sorted lines, but when I want to get rid of the lines for which 3rd field is unique, by comparing to the previous line, I don't get that previous line printed.

sort -k3,3 file.txt | awk 'BEGIN {prev=$3} ($3==prev) {print $0} {prev=$3}'

Which is obvious, but I'm asking for advice how to do it right, cause I have no clue. And Google was not very helpfull either.
 
Another way is to play with the associative arrays:
awk '{a[$3]=a[$3]$0"\n";++b[$3]}END{for(i in a)if(b>1)printf "%s",a}' file.txt

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top