如何从一行中的命令输出字符串中删除已知的最后一部分?
How to remove a known last part from commands output string in one line?
改写 - 我想在同一行中使用 Bash 命令替换和字符串替换。
我的实际命令更长,但这里荒谬地使用 echo 只是为了缩短 "substitution" 并且行为相同 - 错误相同 ;)
我知道我们可以使用 Bash 命令生成它的输出字符串作为另一个命令的参数,如下所示:
echo "$(echo "aahahah</ddd>")"
aahahah</ddd>
我也知道我们可以像这样删除字符串的最后已知部分:
var="aahahah</ddd>"; echo "${var%</ddd>}"
aahahah
我正在尝试编写一个命令,其中一个命令给出一个字符串输出,我想删除已知的最后一部分。
echo "${$(echo "aahahah</ddd>")%</ddd>}"
-bash: ${$(echo "aahahah</ddd>")%</ddd>}: bad substitution
这可能是事情发生的顺序,或者替换只适用于变量或硬编码字符串。但我怀疑只是我遗漏了一些东西,这是可能的。
如何让它发挥作用?
为什么不起作用?
像这样组合你的命令
var=$(echo "aahahah</ddd>")
echo ${var/'</ddd>'}
当使用 $word
或 ${word}
中的美元符号时,它会请求 word
的内容。这称为参数扩展,根据 man bash
.
你可以这样写 var="aahahah</ddd>"; echo "${var%</ddd>}"
: 扩展 var
并在返回值之前执行特殊的后缀操作。
但是,你可以不写echo "${$(echo "aahahah</ddd>")%</ddd>}"
,因为一旦计算$(echo "aahahah</ddd>")
就没有什么可以扩展了。
来自man bash
(我强调):
${parameter%word}
Remove matching suffix pattern. The word is expanded to produce a
pattern just as in pathname expansion. If the pattern
matches a trailing portion of the expanded value of parameter, then
the result of the expansion is the expanded value of parameter
with the shortest matching pattern (the ''%'' case) or the longest matching pattern (the ''%%'' case) deleted.
改写 - 我想在同一行中使用 Bash 命令替换和字符串替换。
我的实际命令更长,但这里荒谬地使用 echo 只是为了缩短 "substitution" 并且行为相同 - 错误相同 ;)
我知道我们可以使用 Bash 命令生成它的输出字符串作为另一个命令的参数,如下所示:
echo "$(echo "aahahah</ddd>")"
aahahah</ddd>
我也知道我们可以像这样删除字符串的最后已知部分:
var="aahahah</ddd>"; echo "${var%</ddd>}"
aahahah
我正在尝试编写一个命令,其中一个命令给出一个字符串输出,我想删除已知的最后一部分。
echo "${$(echo "aahahah</ddd>")%</ddd>}"
-bash: ${$(echo "aahahah</ddd>")%</ddd>}: bad substitution
这可能是事情发生的顺序,或者替换只适用于变量或硬编码字符串。但我怀疑只是我遗漏了一些东西,这是可能的。
如何让它发挥作用? 为什么不起作用?
像这样组合你的命令
var=$(echo "aahahah</ddd>")
echo ${var/'</ddd>'}
当使用 $word
或 ${word}
中的美元符号时,它会请求 word
的内容。这称为参数扩展,根据 man bash
.
你可以这样写 var="aahahah</ddd>"; echo "${var%</ddd>}"
: 扩展 var
并在返回值之前执行特殊的后缀操作。
但是,你可以不写echo "${$(echo "aahahah</ddd>")%</ddd>}"
,因为一旦计算$(echo "aahahah</ddd>")
就没有什么可以扩展了。
来自man bash
(我强调):
${parameter%word}
Remove matching suffix pattern. The word is expanded to produce a pattern just as in pathname expansion. If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the ''%'' case) or the longest matching pattern (the ''%%'' case) deleted.