David Prentice
David Prentice

Reputation: 143

How to use sed to append multiple lines to a file?

Yes I searched the site and I don't think I seen anything to specifically addressed my very (simple I imagine) issue that I just cannot overcome.

I'm taking a Linux class and I have been asked this question:

Use the sed command and a script file to add these lines to the end of the CD_list file:

hard rock:1008:70
misc:1009:22

I have tried over and over, and read the chapter. I can't figure this out.

The file CD_list is created, and I need to append those two above lines to it as shown using a script file. Yup stumped.

Upvotes: 2

Views: 11673

Answers (2)

xeuari
xeuari

Reputation: 68

One possible answer: sed -i 's/^$/hard rock:1008:70\nmisc:1009:22/' CD_list

EDIT: try this instead sed -i '$ a\hard rock:1008:70\nmisc:1009:22' CD_list

I think it's the a command you're after.

Here is a fantastic resource: http://www.grymoire.com/Unix/Sed.html

Upvotes: 4

melpomene
melpomene

Reputation: 85847

Put the following in script.sed:

$a \
hard rock:1008:70\
misc:1009:22

Then run sed -f script.sed CD_list. This will output CD_list and the appended lines to standard out. If you want to modify the file in place, use sed -i -f script.sed CD_list.


Here's how it works: We use $ to match the last line of the file. Then we run the a (append) command, which outputs the text coming after it at the end of the current cycle. Normally a newline would terminate the a command, so we use \ (backslash) to escape the newline and output it as-is.

(Information taken from https://www.gnu.org/software/sed/manual/sed.html#sed-Programs.)

Upvotes: 5

Related Questions