Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

What's the shortest code that does this? I've been doing something like

echo "header" >  tmpfile
cat $file     >> tmpfile
echo "footer" >> tmpfile
mv tmpfile $file

. Is there a more compact way?

share|improve this question
In PowerShell you could do 'header',(gc $file),'footer'|Out-File $file :-P – Joey Jul 20 '11 at 21:37
up vote 2 down vote accepted
echo "header"
cat $file
echo "footer"
} > tmpfile
mv tmpfile $file
share|improve this answer
sed -i -e '1s/^/header\n/' -e '$s/$/\nfooter/' $file

Update: even shorter:

sed -i '1s/^/header\n/;$s/$/\nfooter/' $file

Update: and even shorter (but must be on many lines as 'i' and 'a' commands in 'sed' must be followed by a \<newline>):

sed -i '1i\
footer' $file
share|improve this answer
Knew it was possible to do in sed, but was unsure of the proper syntax to describe last line. Nice one. – Nicholi Jul 21 '11 at 16:35

Well you could use a Here document

tee > /tmp/otherfile <<EOF
$(cat $file)

And then rename.

share|improve this answer

This seems to work in zsh, but unfortunately not in bash.

TMPTXT="header\n"$(cat $file)"\nfooter"
echo $TMPTXT > $file

or in one line:

echo header\\n"$(cat $file)"\\nfooter > $file

(I think this should work in bash as well, except I have some trouble getting the newlines right.)


Using echo -e this also works in bash in one line:

echo -e "header\n$(cat $file)\nfooter"
share|improve this answer
Are you sure the 'echo ... > $file' works in all cases, because if the parameter evaluation is done after the redirection, the 'cat' could print an empty file. I tried it on cygwin and your solution works (parameters seams to be evaluated before the redirection), but is it the same in all shells ? – jfgagne Jul 21 '11 at 9:26
'echo -e "header\n$(cat $file)\nfooter" > $file' works in cygwin, but 'echo -e "header\n$(cat $file)\nfooter" | cat > $file' does not... – jfgagne Jul 21 '11 at 9:28
This is indeed a valid case, I'm not sure if this would always work. I tried this on my Macbook and it seems to work OK (zsh 4.3.11 on OS X 10.7). A safer bet is using the temporary variable, except I haven't gotten that to work in bash (newlines are dropped with echo $(cat $file)). – Tim Jul 21 '11 at 13:41

You must log in to answer this question.

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