icarbajo
icarbajo

Reputation: 351

sed add line at the end of file

I trying to add a line at the end of file (/root/test.conf) with sed. I use FreeBSD and when I try to add a simple line, I always get several errors like:

The file is like this:

#Test
firstLine
secondLine

!p.p
*.*

And I want to add something like this:

(return \n)
!word
other (5 tab between "other" and "/usr/local") /usr/local

If it's not possible with sed, there are another options?

Thank you!

Upvotes: 1

Views: 8462

Answers (4)

Ainz Sama
Ainz Sama

Reputation: 1

I needed something like this recently. I am not sure if anyone will even need this and I am sure there is probably better way to do this.

Disclaimer: I was using FreeBSD and sed there is a little bit different then other os.

So I came up with this: sed -i '' -e '$s/$/\ntext1=\"text2\"/g' /location/file.test

explained: sed -i '' -e

-i extension = Edit files in-place

-e command = Append the editing commands

- s/regular expression/replacement/flags

explained: '$s/$/\ntext1=\"text2\"/g' /location/file.test

$s = last line

$/ = end of line

\ntext1=\"text2\" = add text start with \n = newline followed by text

/g = Make the substitution for all non-overlapping matches

/location/file.test = path of the file you are editing

Alternative examples

at the start of the document: sed -i '' -e '1s/^/text1=\"text2\"\n/g' /location/file.test

at the line 3: sed -i '' -e '3s/^/text1=\"text2\"\n/g' /location/file.test

Upvotes: 0

Gary Aitken
Gary Aitken

Reputation: 291

In the event you have other things to do in sed, and appending at the end is just one of them:

sed -e "\$a A-line-at-the-end.' <infile >outfile
sed -e '$a A-Line-at-the-end.'  <infile >outfile
sed -e '$a\A-line-at-the-end.'  <infile >outfile

Works on linux (ubuntu), not on freebsd.

Upvotes: 3

Tom Fenech
Tom Fenech

Reputation: 74596

It doesn't sound like you need to use sed at all, maybe just cat with a heredoc:

cat >>test.conf <<EOF
whatever you want here

more stuff
EOF

>> opens test.conf in "append" mode, so lines are added to the bottom of the file, and the <<EOF is a heredoc that allows you to pass lines to cat via standard input.

To add literal tabs in the interactive terminal, you can use Ctrl-v followed by Tab.

Upvotes: 2

George Vasiliou
George Vasiliou

Reputation: 6335

You don't need any special tools like sed to add some lines to the end of files.

$ echo "This is last line" >>file 
#or
$ printf "This is last line\n" >>file

works just fine in almost any platform. You might need to escape special characters though, or enclose them in single/double quotes.

Upvotes: 2

Related Questions