bash 过滤输入以删除某些字符/字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11185181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Filter input to remove certain characters/strings
提问by modzello86
I have quick question about text parsing, for example:
我有关于文本解析的快速问题,例如:
INPUT="a b c d e f g"
PATTERN="a e g"
INPUT variable should be modified so that PATTERN characters should be removed, so in this example:
应修改 INPUT 变量,以便删除 PATTERN 字符,因此在此示例中:
OUTPUT="b c d f"
I've tried to use
我试过用
tr -d $x在按“模式”计数的 for 循环中,但我不知道如何为下一次循环迭代传递输出。
edit: How if a INPUT and PATTERN variables contain strings instead of single characters???
编辑:如果 INPUT 和 PATTERN 变量包含字符串而不是单个字符,该怎么办???
回答by choroba
Where does $xcome from? Anyway, you were close:
哪里$x来的呢?无论如何,你很接近:
tr -d "$PATTERN" <<< $INPUT
To assign the result to a variable, just use
要将结果分配给变量,只需使用
OUTPUT=$(tr -d "$PATTERN" <<< $INPUT)
Just note that spaces will be removed, too, because they are part of the $PATTERN.
请注意,空格也将被删除,因为它们是 $PATTERN 的一部分。
回答by Fritz G. Mehner
Pure Bash using parameter substitution:
使用参数替换的纯 Bash:
INPUT="a b c d e f g"
PATTERN="a e g"
for p in $PATTERN; do
INPUT=${INPUT/ $p/}
INPUT=${INPUT/$p /}
done
echo "'$INPUT'"
Result:
结果:
'b c d f'

