Ankit Vallecha Ankit Vallecha - 1 year ago 73
Bash Question

Empty line missing after using echo and sed

I have written one shell script which replaces some properties in a properties file.But after the script is run there is no empty line at the end of file which was present before replacement.
file_content=$(cat $file | sed "s@a=.*@a=b@g") #making a=b
file_content=$(echo "${file_content}" | sed "s@x=.*@x=y@g") #making x=y
echo "${file_content}" > $file is something like


Note there is blank line at the end.These numbers are just for displaying the empty line

Answer Source

From the Bash manual in reference to $(…) Command Substitution (emphasis mine):

Bash performs the expansion by executing command in a subshell environment and replacing the command substitution with the standard output of the command, with any trailing newlines deleted.

So rather than capturing the output of the commands into a variable, you should capture them into a temporary file:

sed "s@a=.*@a=b@g" $file | sed "s@x=.*@x=y@g" > tmp.tmp
mv tmp.tmp $file

Or if you are using GNU sed, you can do it in one line:

sed -i -e "s@a=.*@a=b@g" -e "s@x=.*@x=y@g" $file

The -i means to edit the file in place, so no temporary file is needed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download