Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a file where certain (not all) lines look like so:

Sequence: n

I wish to replace n with the respective line number.

How can I do it with sed?

share|improve this question
By "do it with sed" do you mean "do it with sed" or "do it with any common tool"? Because people say the former and mean the latter about 98% of the time – Michael Mrozek Aug 25 '11 at 16:48
I am specifically curious about sed. – mark Aug 25 '11 at 17:30

It is very simple with awk (thanks to @glenn jackman):

awk '/Sequence: n/ { $2 = NR } { print }' input-file

Regarding sed, I've only been able to do this with a two-pass elaboration (tested with GNU sed and with ssed:):

sed '/^Sequence: n$/{s/n$//p;=;d;}' | sed '/^Sequence: $/{N;s/\n//;}' 

The first inserts the line number in the row after "Sequence: ", the second joins the two lines.

share|improve this answer
I'd write your awk command as: awk '/Sequence: n/ {$2 = NR} {print}' – glenn jackman Aug 25 '11 at 21:22
@glenn jackman: well done, my bad. – enzotib Aug 26 '11 at 7:22

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.