1

I'd like to get the first line out of a file and put it at the beginning of every line of the rest. For example, how do I transform this:

black
widow
card
Friday
berry

into this?:

black: widow
black: card
black: Friday
black: berry

Is it possible to do this without explicitly creating extra files and variables?

3

With simple awk command you can do it:

awk 'NR == 1 {a=$0;next} { printf("%s: %s\n",a,$0)}' file_name
2
  • Thanks, works like a charm! Is it a bad idea to do the same thing with sed?
    – stacko
    Apr 19 '19 at 4:28
  • @stacko see other answer.
    – Prvt_Yadav
    Apr 22 '19 at 14:29
1

This might not be the best way to do it in sed, but:

$ sed '1{h;d;}; G; s/\(.*\)\n\(.*\)/\2: \1/' file
black: widow
black: card
black: Friday
black: berry

Explanation:

  • 1{h;d;} for the first line, copy pattern space to hold space and then delete
  • G append a newline to the contents of the pattern space, and then append the contents of the hold space to that of the pattern space. We now have the right two words in pattern space, but in the wrong order and with the wrong separator (\n instead of :)
  • s/\(.*\)\n\(.*\)/\2: \1/' swap the parts before and after the newline, replacing newline with a colon and space
2
  • Explanation...?
    – Prvt_Yadav
    Apr 19 '19 at 13:51
  • @Prvt_Yadv added ... Apr 19 '19 at 13:58

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.