i have a string like 1.1.1.1.1
, i want to replace all dots with _
character.
i wrote the following program:
#!/bin/bash
var="1.1.1.1.1"
new2=${var/./_}
echo $new2
but it just replaces first dot with _
in the string, so the result is:
1_1.1.1.1
how i can replace all dots with _
?
thanks.
To replace the dots in a string, you need to escape the dot (.) and replace using the replace() method.
$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.
The operator "%" will try to remove the shortest text matching the pattern, while "%%" tries to do it with the longest text matching. Follow this answer to receive notifications.
To replace content in a file, you must search for the particular file string. The 'sed' command is used to replace any string in a file using a bash script. This command can be used in various ways to replace the content of a file in bash. The 'awk' command can also be used to replace the string in a file.
You were pretty close. To replace all matches, use ${var//find/replace}
:
#!/bin/bash
var="1.1.1.1.1"
new2="${var//./_}"
echo "$new2" # prints 1_1_1_1_1
The bash built-ins of the form ${var...}
are called parameter expansions/substitutions. They are documented in detail in the official bash manual. For an alternative explanation, check out bash-hackers.org.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With