Unwanted multiple duplicate lines - sed
There is a task to select addresses from the postgresql database, then connect to the selected addresses via ssh and add a specific line in the right place in the config on each host.
For example, there is a file containing values in the middle of the file, after which you need to insert a new line with a different value:
# grep hostname config.cfg
hostname, port = 2234: Vasya
hostname, ip address: John, 192.168.1.5
hostname: Andrew
Next, for example, after the line
hostname: Andrew
I need to insert a new value on a new line:
hostname: Sheglina
I do it like this (tried for one host first):
for HOST in 192.168.1.1; do ssh $HOST "for VALUE in $(nl -ba /root/config.cfg|grep hostname | tail -1 | awk '{print $1}'); do sed -i $VALUE'a\hostname: Sheglina'/root/config.cfg; done"; done
This command works on a VIRTUAL MACHINE.
# grep hostname config.cfg
hostname, port = 2234: Vasya
hostname, ip address: John, 192.168.1.5
hostname: Andrew
hostname: Sheglina
BUT when I do on a real server, making a selection of ip addresses by filters, then I try to apply this command:
for HOST in $(psql -U postgres name_db -c "SELECT name, ip_address FROM servers ORDER BY ip_address;" | grep -i 'moscow' | awk '{print $5}'); do ssh $HOST "for VALUE in $(nl -ba /root/config.cfg|grep hostname | tail -1 | awk '{print $1}'); do sed -i $VALUE'a\hostname: Sheglina '/root/config.cfg;done"; done
then the hostname: Sheglina line is duplicated through each line in /root/config.cfg, not in one place. I do not need it. I don't understand why this command works for VIRTUAL MACHINE, but for SERVER it doesn't work. And even if I go to a separate node from the cluster and issue a command for the same node, there are still duplicate lines ... What could be the reason?
How it's look in REAL SERVER:
# grep hostname config.cfg
hostname: Sheglina
hostname: Sheglina
hostname: Sheglina
hostname: Sheglina
...
the old lines with the hostname value remained in the file, but the Sheglina line is duplicated through each line for some reason
sed -i $VALUE'a\hostname: Sheglina '
gets passed to the remote shell, the local shell has already expanded$VALUE
to the empty string.