我对 bash 脚本编写还很陌生。如何转换同时包含短语和单个单词的字符串:
flowers yellow "beautiful yellow flowers" nature colors
到一个字符串,每个字符串都有引号,并在它们之间添加逗号:
"flowers", "yellow", "beautiful yellow flowers", "nature", "colors"
最佳答案
这是一个纯粹的 bash
解决方案:
#!/bin/bash
printf -v all '"%s", ' "${@}"
echo "${all%, }"
举个例子:
script.sh flowers yellow "beautiful yellow flowers" nature colors
"flowers", "yellow", "beautiful yellow flowers", "nature", "colors"
说明:
printf -v all '"%s", ' "${@}"
对于命令行上的每个参数,这会将其打印到变量
all
中,并添加引号、逗号和尾随空格。此方法利用 shell 对命令行参数的处理。特别是,shell 将命令行上的双引号字符串解释为单个参数,并且在脚本开始之前 shell 会删除它们的引号。
回显“${all%, }”
变量
all
末尾有一个额外的逗号和空格。这将删除它们并打印结果。
帽子提示:Rici。
替代方案
此 bash
方法较长,但可能更容易自定义:
#!/bin/bash
for s in "$@"
do
s=${s%\"}
s=${s#\"}
all="$all, \"$s\""
done
echo "${all#, }"
举个例子:
$ script.sh flowers yellow "beautiful yellow flowers" nature colors
"flowers", "yellow", "beautiful yellow flowers", "nature", "colors"
说明
for s in "$@";做
这将循环命令行上的每个项目。请注意,在命令行上,双引号字符串是单个项目。每个参数依次分配给变量
s
。s=${s%\"}; s=${s#\"}
这两个语句删除字符串
s
前面或后面的双引号(如果有)。all="$all,\"$s\""
这会将当前参数附加到字符串
all
。完成
这样就完成了循环
回显“${all#, }”
字符串
all
在开头有一个额外的逗号和空格。这将删除它们,然后在标准输出上显示结果。
从另一个脚本调用此示例
tags=(flowers yellow "beautiful yellow flowers" nature colors)
tags=($(bash script.sh "${tags[@]}"))
echo "${tags[@]}"
这会产生输出:
"flowers", "yellow", "beautiful yellow flowers", "nature", "colors"
关于regex - 如何在字符串中的单个单词周围添加引号,而不是在已经有引号的子字符串周围添加引号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26200024/