我很难弄清楚如何sed
在某个分隔符之前剪切文本。
我收到的输出echo
返回类似以下内容:
valueA=TEXT
我想sed
先把文本剪掉=
,只留下文本。
关于如何做到这一点有什么建议吗?
答案1
您还可以使用cut
:
cut -d= -f2- <<< "$yourvar"
或者
some_command | cut -d= -f2-
-d=
将分隔符设置为=
-f2-
接受第二个字段和以下所有字段
答案2
来自@Archemar 的评论,这可能应该是一个答案:
sed -e s/^[^=]*=//
从@Baard Kopperud 的评论来看,该sed
命令可以解释为:
将以 (^) 开头的行 (s/) 替换为除“=”之外的任意数量的字符 (*) ([^=]),后跟不带任何内容 (//) 的等式符号 (=)。这将从行的开头删除所有内容,直到并包括 equal-sing - 只留下“=”后面的内容。如果有多个等号,您需要“[^=]*”...您只想删除第一个等号。如果您只使用“.*”,那么您将剪切到并包括最后一个等号,因为正则表达式“希望”尽可能长,并且从尽可能远的左侧开始。
答案3
我正在接收来自的输出
echo
如果您从变量形成它echo
,则可以使用 shell 的内置字符串操作功能:
# Instead of value=$(echo "$var" | cut -d= -f2-)
value=${var#*=}
这*=
只是一个全局样式的模式,可以*
匹配任何内容。表示#
该模式与要从变量中删除的前缀匹配。
这最终将比从 进行管道传输更快、更可靠echo
,因为它避免了可能给您带来的麻烦xpg_echo
(以及 的其他解析怪癖echo
),并且避免了分叉。
您还可以使用以下方法获取密钥:
key=${var%%=*}
请注意,它%%
是用来匹配的,而不是%
贪婪匹配的。这样,它就不会被=
值中任何潜在的 - 符号绊倒。
语法记录在man bash
, 下Parameter Expansion
:
${parameter#word} ${parameter##word} Remove matching prefix pattern. The word is expanded to produce a pattern just as in pathname expansion. If the pattern matches the beginning of the 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 pat‐ tern (the ``##'' case) deleted. If parameter is @ or *, the pattern removal operation is applied to each positional parame‐ ter in turn, and the expansion is the resultant list. If param‐ eter is an array variable subscripted with @ or *, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list. ${parameter%word} ${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. If parameter is @ or *, the pattern removal operation is applied to each posi‐ tional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with @ or *, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.