Replace one character with another in Bash

2020-01-25 12:47发布

I need to be able to do is replace a space () with a dot (.) in a string in bash.

I think this would be pretty simple, but I'm new so I can't figure out how to modify a similar example for this use.

6条回答
Summer. ? 凉城
2楼-- · 2020-01-25 12:58

Try this

 echo "hello world" | sed 's/ /./g' 
查看更多
再贱就再见
3楼-- · 2020-01-25 13:00

In bash, you can do pattern replacement in a string with the ${VARIABLE//PATTERN/REPLACEMENT} construct. Use just / and not // to replace only the first occurrence. The pattern is a wildcard pattern, like file globs.

string='foo bar qux'
one="${string/ /.}"     # sets one to 'foo.bar qux'
all="${string// /.}"    # sets all to 'foo.bar.qux'
查看更多
萌系小妹纸
4楼-- · 2020-01-25 13:11

You could use tr, like this:

tr " " .

Example:

# echo "hello world" | tr " " .
hello.world

From man tr:

DESCRIPTION
     Translate, squeeze, and/or delete characters from standard input, writ‐ ing to standard output.

查看更多
霸刀☆藐视天下
5楼-- · 2020-01-25 13:12

Try this for paths:

echo \"hello world\"|sed 's/ /+/g'|sed 's/+/\/g'|sed 's/\"//g'

It replaces the space inside the double-quoted string with a + sing, then replaces the + sign with a backslash, then removes/replaces the double-quotes.

I had to use this to replace the spaces in one of my paths in Cygwin.

echo \"$(cygpath -u $JAVA_HOME)\"|sed 's/ /+/g'|sed 's/+/\\/g'|sed 's/\"//g'
查看更多
forever°为你锁心
6楼-- · 2020-01-25 13:14

Use inline shell string replacement. Example:

foo="  "

# replace first blank only
bar=${foo/ /.}

# replace all blanks
bar=${foo// /.}

See http://tldp.org/LDP/abs/html/string-manipulation.html for more details.

查看更多
时光不老,我们不散
7楼-- · 2020-01-25 13:14

Use parameter substitution:

string=${string// /.}
查看更多
登录 后发表回答