Search file, show matches and first line

I have a comma delimited text file that contains the column headers in the first row:

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

Now I need a short command that prints the first line and the corresponding lines. Is there a shorter way than:

 head -n 1 file ; cat file | grep bar 
+4
source share
6 answers

This might work for you:

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

Usually cat file | ... cat file | ... useless, but in this case it keeps the file argument aside and allows you to quickly change the v variable.

Another solution:

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

This should complete the task:

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

Where:

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

Note that this will not print the title bar twice if there is a match in the column names.

+6
source

You can use grouping commands, then pass the column command for pretty-printed

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

What if the first line contains bar too? Then it prints twice with your version. awk solution:

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

If you want the search to look like almost the last element in the string:

 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 is that it is one process.

+3
source

head -n 1 file && grep bar file There may be an even shorter version, but it will be a bit more complicated.

EDIT: according to bobah's comment, I added && between the commands to only have one error for the missing file

+2
source

Here is the shortest command:

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

Source: https://habr.com/ru/post/1398180/


All Articles