Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace dots in a string with a character in bash

Tags:

bash

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.

like image 337
anon Avatar asked Oct 27 '17 21:10

anon


People also ask

How do you replace a dot in a string?

To replace the dots in a string, you need to escape the dot (.) and replace using the replace() method.

What does [- Z $1 mean in Bash?

$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.

What does %% mean in Bash?

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.

How do I find and replace in a string in Bash?

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.


1 Answers

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.

like image 177
Socowi Avatar answered Oct 18 '22 23:10

Socowi