我非常擅长bash脚本编写。如何转换包含短语和单个单词的字符串:
flowers yellow "beautiful yellow flowers" nature colors
到一个字符串,每个字符串都有引号,并在它们之间添加逗号:
"flowers", "yellow", "beautiful yellow flowers", "nature", "colors"
答案 0 :(得分:2)
这是一个纯粹的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会删除它们的引号。
echo "${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 "$@"; do
这会遍历命令行上的每个项目。请注意,在命令行中,双引号字符串是单个项目。反过来,每个参数都分配给变量s
。
s=${s%\"}; s=${s#\"}
这两个语句从字符串s
的前面或后面删除双引号(如果有)。
all="$all, \"$s\""
这会将当前参数追加到字符串all
。
done
这样就完成了循环
echo "${all#, }"
字符串all
在开头有一个额外的逗号和空格。这将删除它们,然后在stdout上显示结果。
tags=(flowers yellow "beautiful yellow flowers" nature colors)
tags=($(bash script.sh "${tags[@]}"))
echo "${tags[@]}"
这会产生输出:
"flowers", "yellow", "beautiful yellow flowers", "nature", "colors"
答案 1 :(得分:0)
使用gnu awk:
s='flowers yellow "beautiful yellow flowers" nature colors'
awk -v RS='"[^"]*"' -v OFS=", " -v ORS= '{for (i=1; i<=NF; i++) printf "\"%s\"%s", $i, OFS;
if (RT) print RT OFS}' <<< "$s"
"flowers", "yellow", "beautiful yellow flowers", "nature", "colors",
答案 2 :(得分:0)
你可以通过下面的Perl one-liner命令
来做到这一点$ s='flowers yellow "beautiful yellow flowers" nature colors'
$ perl -pe 's/"[^"]*"(*SKIP)(*F)|(\S+)/"\1",/g; s/,$//; s/"(?= *")/",/g' <<< "$s"
"flowers", "yellow", "beautiful yellow flowers", "nature", "colors"