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?

  • 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.

  • 2
    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 clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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