Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search file, show matches and first line

Tags:

grep

bash

unix

sed

awk

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
like image 747
grimmig Avatar asked Dec 02 '22 23:12

grimmig


2 Answers

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.

like image 93
jcollado Avatar answered Dec 20 '22 09:12

jcollado


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
like image 22
potong Avatar answered Dec 20 '22 08:12

potong