简体   繁体   English

使用Shell脚本搜索和替换变量字符串

[英]Search and Replace in a variable string with Shell scripts

I am in dilemma about how could I search and replace a particular character in a variable of a shell script. 对于如何在shell脚本变量中搜索和替换特定字符,我感到困惑。

eg I have a condition where I need to pass '~' to the java program but I should pass it as '/~' to avoid it being intercepted as $HOME. 例如,我有一个条件,我需要将'~'传递给Java程序,但我应该将其作为'/~'传递,以避免将其作为$ HOME截获。 I have a shell variable eg $1 = '.-~' and I am passing it directly to the Java program as an argument. 我有一个shell变量,例如$1 = '.-~' ,并将其作为参数直接传递给Java程序。 So how could I modify this variable in such a way that it searches for '~' and if it finds then changes $1 = '.-/~' so as to avoid the error in Java program. 因此,如何修改此变量,使其搜索'~' ,如果找到,然后更改$1 = '.-/~' ,以避免Java程序中的错误。

I tried $(1//~//~) but it gives me an error. 我尝试了$(1//~//~)但它给了我一个错误。

Also this gave me an error. 同样,这给了我一个错误。

sed 's#~#/#g' <<< $x;

To replace a string in a shell variable, you can use var modifiers like this: 要替换shell变量中的字符串,可以使用var修饰符,如下所示:

${YOURVAR/The string you want to search/The string you want to replace to}

By example: 例如:

${HOME/~/world} -> "hello ~" become "hello world"

For both your attempts you have two options: 对于这两种尝试,您都有两个选择:

"${1//\~//~}"  ## ~ in pattern needs to be backslash quoted.

And

sed 's#~#/~#g' <<< "$x"  ## $x should be placed in double quotes to prevent other word splitting or expansions. And you probably forgot ~.

Other versions to replace with \\ instead: 其他版本替换为\\

"${1//\~/\\~}"
sed 's#~#\\~#g' <<< "$x"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM