grimmig
grimmig

Reputation: 1421

Search file, show matches and first line

I've got a comma separated textfile, which contains the column headers in the first line:

column1;column2;colum3
foo;123;345
bar;345;23
baz;089;09

Now I want a short command that outputs the first line and the matching line(s). Is there a shorter way than:

head -n 1 file ; cat file | grep bar

Upvotes: 4

Views: 321

Answers (6)

Hai Vu
Hai Vu

Reputation: 40763

Here is the shortest command yet:

awk 'NR==1||/bar/' file

Upvotes: 1

potong
potong

Reputation: 58483

This might work for you:

cat file | awk 'NR<2;$0~v' v=baz
column1;column2;colum3
baz;089;09

Usually cat file | ... is useless but in this case it keeps the file argument out of the way and allows the variable v to be amended quickly.

Another solution:

cat file | sed -n '1p;/foo/p' 
column1;column2;colum3
foo;123;345

Upvotes: 3

Zsolt Botykai
Zsolt Botykai

Reputation: 51653

What if the first row contains bar too? Then it's printed two times with your version. awk solution:

awk 'NR == 1 { print } NR > 1 && $0 ~ "bar" { print }' FILE

If you want the search sting as the almost last item on the line:

awk 'ARGIND > 1 { exit } NR == 1 { print } NR > 1 && $0 ~ ARGV[2] { print }' FILE YOURSEARCHSTRING 2>/dev/null

sed solution:

sed -n '1p;1d;/bar/p' FILE

The advantage for both of them, that it's a single process.

Upvotes: 3

kev
kev

Reputation: 161864

You can use grouping commands, then pipe to column command for pretty-printing

$ { head -1; grep bar; } <input.txt | column -ts';'
column1  column2  colum3
bar      345      23

Upvotes: 3

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70989

head -n 1 file && grep bar file Maybe there is even a shorter version but will get a bit complicated.

EDIT: as per bobah 's comment I have added && between the commands to have only a single error for missing file

Upvotes: 2

jcollado
jcollado

Reputation: 40414

This should do the job:

sed -n '1p;2,${/bar/p}' file

where:

  • 1p will print the first line
  • 2,$ will match from second line to the last line
  • /bar/p will print those lines that match bar

Note that this won't print the header line twice if there's a match in the columns names.

Upvotes: 6

Related Questions