Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep: Keeping lines that has specific string in certain column

Tags:

grep

sed

awk

I am trying to pick out the lines that have certain value in certain column and save it to an output. I am trying to do this with grep. Is it possible?

My data is looks like this:

apple   5   abcdefd  ewdsf
peach   5   ewtdsfe  wtesdf
melon   1   ewtedf   wersdf
orange  3   qqqwetr  hredfg

I want to pick out lines that have value 5 on its 2nd column and save it to new outputfile.

apple   5   abcdefd  ewdsf
peach   5   ewtdsfe  wtesdf

I would appreciate for help!

like image 306
user3557715 Avatar asked Oct 01 '14 18:10

user3557715


Video Answer


2 Answers

It is probably possible with grep but the adequate tool to perform this operation is definitely awk. You can filter every line having 5 on the second column with

awk '$2 == 5'

Explanation

awk splits it inputs in records (usually a line) and fields (usually a column) and perform actions on records matching certain conditions. Here

awk '$2 == 5'

is a short form for

awk '$2 == 5 {print($0)}'

which translates to

For each record, if the second field ($2) is 5, print the full record ($0).

Variations

If you need to choose dynamically the key value used to filter your values, use the -v option of awk:

awk -v "key=5" '$2 == key {print($0)}'

If you need to keep the first line of the file because it contains a header to the table, use the NR variable that keeps track of the ordinal number of the current record:

awk 'NR == 1 || $2 == 5'

The field separator is a regular expression defining which text separates columns, it can be modified with the -F field. For instance, if your data were in a basic CSV file, the filter would be

awk -F", *" '$2 == 5'

Visit the awk tag wiki to find a few useful information to get started learning awk.

like image 94
Michaël Le Barbier Avatar answered Oct 27 '22 00:10

Michaël Le Barbier


To print when the second field is 5 use: awk '$2==5' file

like image 44
Etan Reisner Avatar answered Oct 27 '22 01:10

Etan Reisner