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

  • A simple echo >> config.txt should do the work if it is just missing the final \n. – Weijun Zhou Mar 20 at 9:18
  • 1
    In this case yes, but it will append a newline if it's missing or not. – pLumo Mar 20 at 9: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 at 14:18
  • @Stéphane, If you have a better idea, you could post it on unix.stackexchange.com/questions/31947/…, or comment on the highest voted answer. – pLumo Mar 20 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
0

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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