0

we gave the following config file ( config.txt )

more config.txt
export var1=345476746

but when I am appending new parameter as

echo "export var2=5645" >> config.txt

we get

more config.txt
export var1=345476746export var2=5645

how to avoid this?

so we get

more config.txt
export var1=345476746
export var2=5645
yael
  • 13,106

3 Answers3

0

Your config.txt has no newline at the end of the file.

The posix standard says there should be:

3.206 Line
A sequence of zero or more non- characters plus a terminating <newline> character.

You can add a new line, e.g.:

sed -i -e '$a\' config.txt

This will add a new line only when there is not already one at the end.

In your case a simple echo >> config.txt would do the job.

pLumo
  • 22,565
  • A simple echo >> config.txt should do the work if it is just missing the final \n. – Weijun Zhou Mar 20 '19 at 09:18
  • 1
    In this case yes, but it will append a newline if it's missing or not. – pLumo Mar 20 '19 at 09:27
  • It's quite inefficient though and is not without side effect (like breaking symlinks, hardlinks, possibly changing file owership) as it makes full copy of the file. – Stéphane Chazelas Mar 20 '19 at 14:18
  • @Stéphane, If you have a better idea, you could post it on https://unix.stackexchange.com/questions/31947/how-to-add-a-newline-to-the-end-of-a-file, or comment on the highest voted answer. – pLumo Mar 20 '19 at 14:34
0

Probably you should have inserted the text export var1=345476746 with -n option initially.

-n do not output the trailing newline

Example :

echo -n "export var1=345476746" > config.txt
echo "export var2=5645" >> config.txt

Results :

# more config.txt 
export var1=345476746export var2=5645
Siva
  • 9,077
0

The easiest way to add a newline char is with echo.

echo >> config.txt
echo "export var2=5645" >> config.txt