gpt4 book ai didi

bash - 如何在 Bash 中拆分带引号的字符串?

转载 作者:行者123 更新时间:2023-11-29 09:25:06 25 4
gpt4 key购买 nike

很少questions关于如何通过给定的分隔符在 Bash 脚本中拆分字符串的很好的答案。

我的问题是我得到一个包含空格分隔字符串的文件,可能被引用,例如

foo bar "foo bar baz" baz

我想将其分为 4 个值 foobarfoo bar bazbaz

如何根据引号将这些输入拆分为 Bash 数组?

最佳答案

默认情况下,bash shell 不提供多字符 IFS 支持来分隔,但由于它是我们正在处理的文件,我们可以使用 GNU Awk 支持 FPAT 来定义如何处理我们正在处理的每个单词。

来自 Defining Fields by Content 下的 GNU Awk 手册页

Normally, when using FS, gawk defines the fields as the parts of the record that occur in between each field separator. In other words, FS defines what a field is not, instead of what a field is. However, there are times when you really want to define the fields by what they are, and not by what they are not.

后半部分是当我们需要使用FPAT时,为了您对空格分隔的字符串和双引号内的字符串的要求,我们定义了一个模式如下,意思是任何不是空格的东西( or) 包含内部双引号但不是双引号。

FPAT = "([^[:space:]]+)|("[^"]+")"

但是要将它作为字符串写入 Awk,您需要转义上面的双引号,

awk 'BEGIN{FPAT = "([^[:space:]]+)|(\"[^\"]+\")"}{for(i=1;i<=NF;i++) print $i}' myFile

这将在单独的一行中打印您输入的每个单词,如下所示,

foo
bar
"foo bar baz"
baz

从这里开始,要存储在 bash 上下文中,您只需要进程替换和 mapfile 命令,

mapfile -t newArray < <(awk 'BEGIN{FPAT = "([^[:space:]]+)|(\"[^\"]+\")"}{for(i=1;i<=NF;i++) print $i}' myFile)

然后你可以将数组打印为

declare -p newArray 

(或)显式打印

for item in "${newArray[@]}"; do
printf '%s\n' "$item"
done

关于bash - 如何在 Bash 中拆分带引号的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47434200/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com