Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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
add comment

3 Answers

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
add comment

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
add comment

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
add comment

Your Answer

 
discard

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.