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.

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I do have a question though, is there anyway I could replace an enter/return in the string?
Can u provide a sample input and output? Now you r getting the different addresses in one line... is that the concern?
Input: "172.16.0.25 (ENTER)172.16.0.25" Output: "172.16.0.25 and 172.16.0.26"
You can use sed ':a;N;$!ba;s/\n/ and /g' .Refer stackoverflow.com/questions/1251999/…
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.)

2 Comments

and the second one returns " "
Hmm... could be something with Raspian... I believe it works on my end :(
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.

Comments

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)

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.