Patrick Cook
Patrick Cook

Reputation: 498

In a bash script, replace character in string with multiple characters

I want to replace "." in this result: "172.16.0.25" with " dot ".

Here is my code:

#!/bin/bash    
connection=`netstat -tn | grep :1337 | awk '{print $5}' | cut -d: -f1`
#this returns "172.16.0.25"
replace=" dot "
final=${connection/./$replace}
echo "$final"

Which returns: test.sh: 4: test.sh: Bad substitution

I tried using tr '.' ' dot ' but that only replaced the '.' with a space (' ')

I know this is a really dumb question, but I'm new to Shell Script.

Also, if it changes anything, I'm on a Raspberry Pi 2 running Raspbian.

Upvotes: 0

Views: 2016

Answers (5)

rici
rici

Reputation: 241871

That line looks fine to me (although it will only replace the first dot; use ${connection//./$replace} to replace all of them), so the most likely thing is that you're not actually using bash.

The bash error message has a lower case b in bad substitution and puts the word line before the line number. The error message shown looks like it is coming from /bin/sh.

If you are running the script with the command

sh test.sh

then the system will use /bin/sh instead of /bin/bash.

Upvotes: 2

Jahid
Jahid

Reputation: 22438

You can simply use:

final="${connection//./$replace}"

Example:

#!/bin/bash
connection="172.16.0.25"
replace=" dot "
final="${connection//./$replace}"
echo "$final"

Output:

172 dot 16 dot 0 dot 25

Upvotes: 0

ring bearer
ring bearer

Reputation: 20783

While @Amadan's answer nails it, I am posting a variation(just for enthusiasts), risking negative votes :)

connection=$(netstat -tn | grep :1337 | awk '{gsub("\.","dot", $5); print $5}' | cut -d: -f1)

Upvotes: 1

Arjun Mathew Dan
Arjun Mathew Dan

Reputation: 5298

You can do the same with awk alone :

netstat -tn | awk '/:1337/{sub(/:.*/,"",$5);gsub(/\./," dot ",$5);print $5}'

If pattern :1337 is matched, take the 5th field. Now remove the :number part. Also replace . with dot and print the field.

Upvotes: 2

Amadan
Amadan

Reputation: 198436

connection=`netstat -tn | grep :1337 | awk '{print $5}' | cut -d: -f1 | sed 's/\./ dot /g'`

You can even simplify by staying in awk:

connection=`netstat -tn | awk '/1337:/ && !x { split($5, a, /:/); x = a[1]; gsub(/[.]/, " dot ", x); print x }'`

(I added && !x to make sure only one row is fetched, just in case.)

Upvotes: 2

Related Questions