【发布时间】:2021-01-04 16:23:36
【问题描述】:
如何在 AWK 语句后添加 echo 命令? 我有一个字符串变量,想在它的末尾添加一个单词。 我在脚本中写这个,不想创建/保存到任何文件。 另一种可能性是,如果我可以将 echo 命令的输出保存到局部变量中以供以后使用。
my_value="the second player is the winner"
echo "$my_value" | awk '{sub(/winner/,"first loser.")}1' | 'Unless they win'
是否可以在 echo 命令的末尾添加一个单词/变量? 所以输出看起来像这样。
the second player is the first loser. Unless they win
更新:
如果我有一个像上面这样的字符串,并且我想将第二个玩家更改为第一个玩家,还可以添加另一个 echo 命令来结束。这就是我之前的意思。
'''
my_value1="除非他们输了"
my_value="第二个玩家是赢家"
回显“$my_value”| awk '{sub(/second/,"first")}1' | $my_value1
'''
使用第二个变量或输入另一个带有单词的回显“”更容易吗?
【问题讨论】:
-
所以使用
sub(/winner/,"first loser unless they win") -
或者忘记
awk而只是echo ${myvalue/winner/first loser unless they win}使用bash 提供的内置带有子字符串替换的参数扩展。 -
echo "$my_value" | awk '{sub(/winner/,"first loser"); printf $0} END{printf " %s\n", "unless they win"}'? -
@DavidC.Rankin 或者只是简单的 POSIX 字符串扩展
echo "${myvalue%winner}first loser unless they win" -
是的,这也是个不错的选择。