[英]How to Convert String in a Text File into Array in Bash
I have text file containing quotes inside single quotes. 我有包含单引号内引号的文本文件。 They are "not" one liners.
他们是“不是”一个班轮。 eg there may be two quotes in same line, but all quotes are inside single quotes like
例如,同一行中可能有两个引号,但所有引号都在单引号内,例如
'hello world' 'this is the second quotes' 'and this is the third quoted text'
how can I create an array and making each quoted text an element of the array. 如何创建数组并使每个引用的文本成为数组的元素。 I've tried using
我试过使用
declare -a arr=($(cat file.txt))
but that makes it space separated. 但这使它们之间存在空间分隔。 assigns each word an element in the array
为每个单词分配数组中的一个元素
If you have bash v4.4 or later, you can use xargs
to parse the quoted strings and turn them into null-delimited strings, then readarray
to turn that into a bash array: 如果您使用的是bash v4.4或更高版本,则可以使用
xargs
解析加引号的字符串,并将其转换为以空分隔的字符串,然后使用readarray
将其转换为bash数组:
readarray -t -d '' arr < <(xargs printf '%s\0' <file.txt)
If you have an older version of bash, you'll have to create the array element-by-element: 如果您使用较旧的bash版本,则必须逐元素创建数组:
arr=( )
while IFS= read -r -d '' quote; do
arr+=( "$quote" )
done < <(xargs printf '%s\0' <file.txt)
Note that xargs
quote syntax is a little different from everything else (of course). 请注意,
xargs
引用语法与其他所有语法(当然)有所不同。 It allows both single- and double-quoted strings, but doesn't allow escaped quotes within those strings. 它允许单引号和双引号的字符串,但不允许在这些字符串中使用转义引号。 And it probably varies a bit between versions of
xargs
. xargs
版本之间可能xargs
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.