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

标签 regex linux string bash unix

我对 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/

相关文章:

javascript - 提取十进制数列表

python - 使用 Python 3、正则表达式和随机数解析文本文件

linux - Bash 脚本在一个文件中查找单词,但在另一个文件中找不到。给定两个文件

linux - 在 NixOS 上即时更改 X11 dpi

C++如何创建 'bind'字符串文本替换方法?

regex - Vim:反转字符串(按字)

r - 从字符串末尾开始匹配

sql-server - SQL Server 基于模式的字符串提取

linux - 使用剪切和粘贴交换列

sql - 从 SQL 中的字符串中选择不同的最高级别目录