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 prefix all the lines of a file (except first line) using the first word in a file.

Input:

x.o: x.cpp /u/a.h 
/b.h \
/c.h \

output:

x.o: x.cpp /u/a.h \
x.o: /b.h \
x.o: /c.h \

Can anyone please help me how to solve the above using sed?

share|improve this question
add comment

2 Answers

up vote 3 down vote accepted

You can do it like this with GNU sed:

sed -r '1 {h; s/ .*//; x}; 1!{G; s/([^\n]*)\n(.*)/\2 \1/}' infile

Or as a separate script:

parse.sed

1 {                         # run block for first line only
  h                         # save copy of line in hold space
  s/ .*//                   # remove redundant part
  x                         # swap prefix to hold space
}

1! {                        # when not first line
  G                         # append prefix to pattern space
  s/([^\n]*)\n(.*)/\2 \1/   # reorganize so prefix is the prefix
}

Run it like this:

 sed -rf parse.sed infile

Output:

x.o: x.cpp /u/a.h 
x.o: /b.h \
x.o: /c.h \
share|improve this answer
    
Thank you. This works great. –  Naga May 24 '13 at 13:35
    
+1 I'm always impressed by non-trivial sed scripts. –  glenn jackman May 24 '13 at 19:19
add comment

Perl solution:

perl -pe 'print $prefix; ($prefix) = /^(.+? )/ if 1..1' INPUT.TXT
share|improve this answer
    
thank you. I'm not sure whether I can use above solution in a makefile. I want to use sed command to achieve above. –  Naga May 24 '13 at 12:20
    
@Naga, there's nothing magic about sed in a makefile. perl (or awk or ...) is just an external tool like sed. –  glenn jackman May 24 '13 at 19:17
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.