管道 bash 字符串操作

Mia*_*ati 12 bash string variable-substitution

我读过一些其他管道 bash 字符串操作问题,但它们似乎是专门的应用程序。

本质上,有没有办法让下面的事情更简单?

代替

$ string='hello world'; string2="${string// /_}"; echo "${string2^^}"
HELLO_WORLD
Run Code Online (Sandbox Code Playgroud)

就像是

$ echo 'hello world' | $"{-// /_}" | "${ -^^}"
HELLO_WORLD
Run Code Online (Sandbox Code Playgroud)

编辑 如果可能的话,我有兴趣保持在 bash 操作中以保持速度(而不是 sed/awk,它们倾向于大大减慢我的脚本速度)

编辑2:@jimmij

我喜欢第二个例子并引导我创建一个函数。

bash_m() { { read x; echo "${x// /_}"; } | { read x; echo "${x^^}"; }; }
echo hello world | bash_m
HELLO_WORLD
Run Code Online (Sandbox Code Playgroud)

PM *_*ing 9

吉米说的话。他的最后一个例子是最接近你在管道表达式中尝试的东西。

这是该主题的一个变体:

echo 'hello world'|echo $(read s;s=${s^^};echo ${s// /_})
Run Code Online (Sandbox Code Playgroud)

我倾向于使用tr,因为它非常快。

echo 'hello world'|tr ' [:lower:]' '_[:upper:]'
Run Code Online (Sandbox Code Playgroud)

我想 bash 不允许嵌套参数扩展是一种耻辱;OTOH,使用这种嵌套表达式很容易导致代码阅读起来很痛苦。除非您真的需要尽可能快地运行,否则最好编写易于阅读、理解和维护的代码,而不是像调试 PITA 那样看起来很聪明的代码。如果你真的必要的事情以最快的速度,你应该使用编译后的代码,做的脚本。


jim*_*mij 7

您不能以这种方式传递参数扩展。当您在表单中x使用$符号时"${x}",它必须是真正的变量名,而不是标准输入,至少不是 in bash。在zsh您可以通过以下方式进行嵌套替换参数:

$ x=''hello world'
$ echo ${${x// /_}:u}
HELLO_WORLD
Run Code Online (Sandbox Code Playgroud)

(注::uzsh一样^^bash

在 bash 中嵌套是不可能的,我认为您所写的问题是最好的,但是如果出于任何奇怪的原因您需要将管道包含到等式中,那么您可能想尝试以下操作:

$ echo 'hello world' | { read x; echo "${x// /_}"; } | { read y; echo "${y^^}"; }
HELLO_WORLD
Run Code Online (Sandbox Code Playgroud)