Add new line at beginning and end of a file

Hi,

I have a specific requirement to add text at the beginning and end of a plain text file. I tried to use "sed" with '1i' and '$a' flags but these required two separate "sed" commands separated with "|".
I am looking for some command/option to join these two in single command parameter.

Sample file --

1
2
3
4

Expected output --

BEGIN
1
2
3
4
END

Thanks in advanced.

Try:

{
  echo BEGIN
  cat yourfile
  echo END
} > newfile

Simple method:-

echo "BEGIN" > /path/to/file/append_text
cat /your/path/to/yourfile/your_existing_file >> /path/to/file/append_text
echo "END" >> /path/to/file/append_text

With sed:

sed '1 i\
BEGIN
$ a\
END
' file

Is it possible to have the entire command in single line?

Thanks for your time.

Yes :wink:

{ echo BEGIN; cat yourfile; echo END;} > newfile

or

{ echo BEGIN; cat; echo END;} < yourfile > newfile

---- OR ----

awk 'BEGIN{print "BEGIN"} 1; END{ print "END" }' yourfile > newfile

GNU sed:

sed '1s/^/BEGIN\n/; $s/$/\nEND/' yourfile > newfile

Not with a standard sed. (I even found a sed version that needs another newline after the END.)
But a recent GNU sed takes

sed -e '1iBEGIN' -e '$aEND' file