Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print specific line number only if match in sed

How do you print a (specific) line only if there is a match in sed (Linux stream editor)? Let's say I have line three that I would like to print only if it meets the match criteria; how can I print this?

I am piping a command's output to sed, and would prefer not to use sed's output to pipe to sed again:

| sed -ne ''"$currline"'p' | sed -n '/state/p'`

Also, I was assigning the output to a variable with backticks.


Given inputs A and B, and the search pattern state, the output for A should be the line 3 stateless (note that 3 is part of the data), and for B should be nothing:

Input A              Input B
1 state              1 state
2 statement          2 statement
3 stateless          3 statless
4 stated             4 stated
5 estate             5 estate
like image 758
user176692 Avatar asked Dec 11 '22 19:12

user176692


1 Answers

sed -n '3{/state/p;}' $file

The 3 matches line 3; the actions on line 3 are 'if you find /state/, print'; the -n prevents general printing of lines.

Also, you should avoid backticks; it is better to use the var=$(cmd1 | cmd2) notation than var=`cmd1 | cmd2` notation.

like image 121
Jonathan Leffler Avatar answered Feb 19 '23 09:02

Jonathan Leffler