Overwrite a file with an edited version in bash

2

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?

Mark

Posted 2011-07-20T21:26:52.850

Reputation: 313

1In PowerShell you could do 'header',(gc $file),'footer'|Out-File $file :-P – Joey – 2011-07-20T21:37:57.050

Answers

3

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

garyjohn

Posted 2011-07-20T21:26:52.850

Reputation: 29 085

3

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

jfg956

Posted 2011-07-20T21:26:52.850

Reputation: 1 021

Knew it was possible to do in sed, but was unsure of the proper syntax to describe last line. Nice one. – Nicholi – 2011-07-21T16:35:48.040

2

Well you could use a Here document

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

And then rename.

Nicholi

Posted 2011-07-20T21:26:52.850

Reputation: 628

0

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"

Tim

Posted 2011-07-20T21:26:52.850

Reputation: 1 642

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 ? – jfg956 – 2011-07-21T09:26:49.090

'echo -e "header\n$(cat $file)\nfooter" > $file' works in cygwin, but 'echo -e "header\n$(cat $file)\nfooter" | cat > $file' does not... – jfg956 – 2011-07-21T09:28:20.417

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 – 2011-07-21T13:41:07.020