Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

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 want to replace some lines, but somehow I would like to add line number to the end of replaced line.

s/display/echo print {LINENUMBER}/

input file:
lorem ipsum
display

output:
lorem ipsum
echo print 2

Can I do this with sed ?

Thanks in advance.

Cs.

share|improve this question

You can use sed = function to write the line number on a line by itself and sed d function to delete the matching pattern. So :

sed '/^display$/{=
d
}' [input file]

will output :

lorem ipsum
2

Assuming you don't have numbers on a line by themselves in the original file you can chain a second sed command to add the ‘echo print’ for those lines, something like :

sed  's/^(\d+)$/echo print \1/'

although the exact syntax may change depending on your system (\d not always being available and so on...)

sed is probably not the simplest tool to do that.

share|improve this answer

I would do that with awk:

awk '{if($0=="display") {print "echo print",NR} else print $0}' < file
share|improve this answer
    
I think awk way is more readable, thanks – user2013619 Jun 23 '13 at 21:25
1  
+1, although I would write it a little less C-like: awk '/display/ {print "echo print", NR; next} 1' file – glenn jackman Jun 23 '13 at 22:52

Perl solution:

perl -pe '$_ = "echo print $.\n" if /display/' input
share|improve this answer
    
thanks for your help – user2013619 Jun 23 '13 at 21:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .