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?

link|improve this question

1  
In PowerShell you could do 'header',(gc $file),'footer'|Out-File $file :-P – Joey Jul 20 '11 at 21:37
feedback

4 Answers

up vote 2 down vote accepted
{
echo "header"
cat $file
echo "footer"
} > tmpfile
mv tmpfile $file
link|improve this answer
feedback
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\
header
;$a\
footer' $file
link|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
feedback

Well you could use a Here document

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

And then rename.

link|improve this answer
feedback

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.)

EDIT:

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

echo -e "header\n$(cat $file)\nfooter"
link|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
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.