Home > Software engineering >  How to use sed command to replace word in file
How to use sed command to replace word in file

Time:10-30

I have a text file:

org.jitsi.videobridge.xmpp.user.shard-1.HOSTNAME=localhost
org.jitsi.videobridge.xmpp.user.shard-1.DOMAIN=auth.jc.name.com
org.jitsi.videobridge.xmpp.user.shard-1.USERNAME=name
org.jitsi.videobridge.xmpp.user.shard-1.PASSWORD=Hfr*7462
org.jitsi.videobridge.xmpp.user.shard-1.MUC_JIDS=JvbBredjoy@internal.auth.jc.name.com
org.jitsi.videobridge.xmpp.user.shard-1.MUC_NICKNAME=7896aee5-fgre-4b02-4569-0bcc75ed1d0d

I created a bash script:

#!/bin/bash
DPATH="/etc/jitsi/videobridge/sip-communicator.properties"
k=$(grep -o 'shard-1' $DPATH) # shard ends by a number#
i=$(grep -o 'shard-1' $DPATH | cut -c7)
m=$((i 1))
n="shard-$m"
sed -i "s|${k}|${n}|g" $DPATH

But I get error:

/home/scripts# ./shard_number
./shard_number: line 5: 1
1
1
1
1
1: syntax error in expression (error token is "1
1
1
1
1")
sed: -e expression #1, char 9: unterminated `s' command

Could you please help to solve this issue? Thank you.

CodePudding user response:

If you call your script with bash -x /path/to/your/script or add set -x somewhere at the start of your script (after the #!shebang, but before the commands you want to debug), you will see that your grep commands return not a single 'shard-1' but rather one 'shard-1' per line :

   grep -o shard-1 /etc/jitsi/videobridge/sip-communicator.properties
  k='shard-1
shard-1
shard-1
shard-1
shard-1
shard-1'

Once cut, that gives the 1\n1\n1\n1\n1\n string that is mentionned in your error output as an invalid token for the $(( ... )) expression, which also breaks the syntax of your sed substitution :

   cut -c7
   grep -o shard-1 /etc/jitsi/videobridge/sip-communicator.properties
  i='1
1
1
1
1
1'

Make that string a single number (for instance piping your grep into sort -u to unicize all the shards found) and your script will work just fine :

#!/bin/bash
DPATH="/etc/jitsi/videobridge/sip-communicator.properties"
k=$(grep -o 'shard-1' $DPATH | sort -u) # shard ends by a number#
i=$(grep -o 'shard-1' $DPATH | sort -u | cut -c7)
m=$((i 1))
n="shard-$m"
sed -i "s|${k}|${n}|g" $DPATH

You can try it here. Also check this test if you want to see your initial script debugged.

  • Related