Patrick Cook Patrick Cook - 4 years ago 145
Bash Question

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

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

Here is my code:

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

Which returns: 4: 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 knew to Shell Script.

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download