Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Always include first line in grep

Tags:

grep

bash

I often grep CSV files with column names on the first line. Therefore, I want the output of grep to always include the first line (to get the column names) as well as any lines matching the grep pattern. What is the best way to do this?

like image 782
jhourback Avatar asked Apr 01 '12 23:04

jhourback


People also ask

How do I grep the first line of a file in Linux?

sed ( sed 1q or sed -n 1p ) and head ( head -n 1 ) are the more appropriate tools for printing the first line from a file. For printing the last line of a file, you have tail -n 1 or sed -n '$p' .

How do I stop grep At first match?

The grep command has an -m or --max-count parameter, which can solve this problem, but it might not work like you'd expect. This parameter will make grep stop matching after finding N matching lines, which works great as it will limit the output to one line, always containing the first match.

How do you grep a specific line?

The -n ( or --line-number ) option tells grep to show the line number of the lines containing a string that matches a pattern. When this option is used, grep prints the matches to standard output prefixed with the line number. The output below shows us that the matches are found on lines 10423 and 10424.


2 Answers

sed:

sed '1p;/pattern/!d' input.txt 

awk:

awk 'NR==1 || /pattern/' input.txt 

grep1:

grep1() { awk -v pattern="${1:?pattern is empty}" 'NR==1 || $0~pattern' "${2:-/dev/stdin}"; } 
like image 148
kev Avatar answered Oct 01 '22 18:10

kev


grep doesn't really have a concept of line number, but awk does, so here's an example to output lines contain "Incoming" - and the first line, whatever it is:

awk 'NR == 1 || /Incoming/' foo.csv 

You could make a script (a bit excessive, but). I made a file, grep+1, and put this in it:

#!/bin/sh pattern="$1" ; shift exec awk 'NR == 1 || /'"$pattern"'/' "$@" 

Now one can:

./grep+1 Incoming 

edit: removed the "{print;}", which is awk's default action.

like image 33
Alex North-Keys Avatar answered Oct 01 '22 20:10

Alex North-Keys