0

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.

Piotr Król
  • 3,350
  • 2
  • 23
  • 25
Patrick Cook
  • 458
  • 12
  • 27

5 Answers5

2
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.)

Amadan
  • 191,408
  • 23
  • 240
  • 301
2

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.

Arjun Mathew Dan
  • 5,240
  • 1
  • 16
  • 27
2

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.

Jahid
  • 21,542
  • 10
  • 90
  • 108
rici
  • 234,347
  • 28
  • 237
  • 341
1

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)
ring bearer
  • 20,383
  • 7
  • 59
  • 72
0

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
Jahid
  • 21,542
  • 10
  • 90
  • 108