3

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?

0

2 Answers 2

3

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 \
1
  • +1 I'm always impressed by non-trivial sed scripts. Commented May 24, 2013 at 19:19
2

Perl solution:

perl -pe 'print $prefix; ($prefix) = /^(.+? )/ if 1..1' INPUT.TXT
2
  • 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
    Commented May 24, 2013 at 12:20
  • @Naga, there's nothing magic about sed in a makefile. perl (or awk or ...) is just an external tool like sed. Commented May 24, 2013 at 19:17

You must log in to answer this question.

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