如何在字符串中的单个单词周围加引号,而不是在已经有引号的子字符串周围?

时间:2014-10-05 05:48:57

标签: regex linux string bash unix

我非常擅长bash脚本编写。如何转换包含短语和单个单词的字符串:

flowers yellow "beautiful yellow flowers" nature colors

到一个字符串,每个字符串都有引号,并在它们之间添加逗号:

"flowers", "yellow", "beautiful yellow flowers", "nature", "colors"

3 个答案:

答案 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"