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
  • 12,598
  • 51
  • 169
  • 303
  • 2
    `config.txt` has no [newline at the end of the file](https://stackoverflow.com/questions/729692/why-should-text-files-end-with-a-newline). Fix that or simply add one before adding `var2`. – pLumo Mar 20 '19 at 08:47
  • still not understand how to add "\n" on each line , seems that last line isn't with "\n" – yael Mar 20 '19 at 08:55
  • If your text file is generated by common text editors in Unix, there should be a newline in the end of the file because that is required by the POSIX standard. In `vim`, files without `\n` in the last line is indicated in the status line by `[noeol]`. – Weijun Zhou Mar 20 '19 at 09:16
  • possible duplicate of [How to add a newline to the end of a file?](//unix.stackexchange.com/q/31947) – Stéphane Chazelas Mar 20 '19 at 14:15
  • See also [What's the point in adding a new line to the end of a file?](//unix.stackexchange.com/q/18743) – Stéphane Chazelas Mar 20 '19 at 14:15

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,231
  • 2
  • 41
  • 66
  • 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,017
  • 8
  • 56
  • 86
0

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

echo >> config.txt
echo "export var2=5645" >> config.txt
Ken Jackson
  • 307
  • 1
  • 5