Replace spaces with underscores through BASH

Suppose I have a string, $ str. I want $ str to be edited so that all spaces in it are replaced with underscores.

Example

a="hello world" 

I need a final conclusion

 echo "$a" 

hello_world

+6
source share
4 answers

You can try the following:

 str="${str// /_}" 
+17
source

Pure bash:

 a="hello world" echo "${a// /_}" 

OR tr:

 tr -s ' ' '_' <<< "$a" 
+8
source
 $ a="hello world" $ echo ${a// /_} hello_world 

According to bash (1):

 ${parameter/pattern/string} 

Template replacement. The template is expanded to create the template in the same way as in the path extension. The parameter is expanded and the longest match of the template with its value is replaced with a string. If the pattern starts with /, all pattern matches are replaced
with a string. Usually only the first match is replaced. If the template starts with C #, it must match at the beginning of the extended parameter value. If the pattern starts with%, it must match at the end of the extended parameter value. If the string is NULL, pattern matches are deleted and the pattern / next pattern can be omitted. If the parameter is @ or *, the substitution operation is applied in each positional parameter in turn, and the extension is the resulting list. If the parameter is an array variable, adjusted using @ or *, the substitution operation is applied to each member of the array in turn, and the extension is the resulting list.

+5
source

With sed , counting directly from a variable:

 $ sed 's/ /_/g' <<< "$a" hello_world 

And to save the result, you should use the syntax var=$(command) :

 a=$(sed 's/ /_/g' <<< "$a") 

For completeness, with awk this can be done as follows:

 $ a="hello my name is" $ awk 'BEGIN{OFS="_"} {for (i=1; i<NF; i++) printf "%s%s",$i,OFS; printf "%s\n", $NF}' <<< "$a" hello_my_name_is 
+3
source

Source: https://habr.com/ru/post/956950/


All Articles