Numbering lines matching the pattern using sed

2019-03-12 12:56发布

I'm writing the script that searches for lines that match some pattern. I must use sed for this script. This works fine for searching and printing matched lines:

sed -n /PATTERN/p

However, I'd also like to print the matched lines number in front of the line itself. How can I do that using sed?

标签: shell unix sed
6条回答
别忘想泡老子
2楼-- · 2019-03-12 13:16

You can use grep:

grep -n pattern file

If you use = in sed the line number will be printed on a separate line and is not available in the pattern space for manipulation. However, you can pipe the output into another instance of sed to merge the line number and the line it applies to.

sed -n '/pattern/{=;p}' file | sed '{N;s/\n/ /}'
查看更多
何必那么认真
3楼-- · 2019-03-12 13:20

Here's the simplest way:

awk '{print ln++  ":  "  $0 }' 
查看更多
\"骚年 ilove
4楼-- · 2019-03-12 13:21

Switch to awk.

BEGIN {
  ln=0
}

$0 ~ m {
  ln+=1
  print ln " " $0
  next
}

{
  print $0
}

...

awk -f script.awk -v m='<regex>' < input.txt
查看更多
Melony?
5楼-- · 2019-03-12 13:31

Using Perl:

perl -ne 'print "$.: $_" if /regex/' input.file

$. contain line number. If input file contains:

record foo
bar baz
record qux

This one-liner: perl -ne 'print "$.: $_" if /record/' input.file will print:

1: record foo
3: record qux

Or if you just want total number of lines matched a pattern use:

perl -lne '$count++ if /regex/; END { print int $count }' input.file

查看更多
甜甜的少女心
6楼-- · 2019-03-12 13:34

= is used to print the line number.

sed -n /PATTERN/{=;p;}
查看更多
对你真心纯属浪费
7楼-- · 2019-03-12 13:35

For sed, use following to get line number

sed -n /PATTERN/= 
查看更多
登录 后发表回答