[英]Return awk split array to a bash variable
I have a requirement to split a string on a multi-character delimiter and return the values into an array in Bash for further processing我需要在多字符分隔符上拆分字符串并将值返回到 Bash 中的数组中以供进一步处理
IFS can take a single character delimiter. IFS 可以采用单个字符分隔符。
a="2;AAAAA;BBBBB;1111_MultiCharDel_2;CCCC;DDDDDD;22222_MultiCharDel_2;EEEE;FFFFFFF;22222"
awk'{split($0,ArrayDeltaMulDep,"_MultiCharDel_")}' <<< $a
The input string can have several substrings separated by the MultiCharDel delimiter.输入字符串可以有多个由 MultiCharDel 分隔符分隔的子字符串。
How can i access this array ArrayDeltaMulDep fur further processing in Bash?如何在 Bash 中访问这个数组 ArrayDeltaMulDep fur 进一步处理?
Your example string, a
, does not contain newlines.您的示例字符串
a
不包含换行符。 If that is true in general, then:如果这在一般情况下是正确的,那么:
a="2;AAAAA;BBBBB;1111_MultiCharDel_2;CCCC;DDDDDD;22222"
readarray -t b <<< "${a//MultiCharDel/$'\n'}"
We can verify that this split the string properly using declare -p
to show the value of b
:我们可以使用
declare -p
来验证这是否正确拆分了字符串以显示b
的值:
$ declare -p b
declare -a b=([0]="2;AAAAA;BBBBB;1111_" [1]="_2;CCCC;DDDDDD;22222")
How it works:这个怎么运作:
readarray -tb
This reads lines from stdin and puts then in a bash array b
.这会从 stdin 读取行,然后将其放入 bash 数组
b
。
<<< "${a//MultiCharDel/$'\\n'}"
${a//MultiCharDel/$'\\n'}
uses pattern substitution to replace MultiCharDel
with a newline character. ${a//MultiCharDel/$'\\n'}
使用模式替换将MultiCharDel
替换为换行符。 <<<
provides the result as stdin to the command readarray
. <<<
将结果作为 stdin 提供给命令readarray
。
A bash string will never contain a null character (hex 00). bash 字符串永远不会包含空字符(十六进制 00)。 Using GNU sed:
使用 GNU sed:
b=()
while read -d '' -r line
do
b+=("$line")
done < <(sed 's/MultiCharDel/\x00/g; s/$/\x00/' <<<"$a")
This again creates an array with the desired splitting:这再次创建了一个具有所需拆分的数组:
$ declare -p b
declare -a b=([0]="2;AAAAA;BBBBB;1111_" [1]="_2;CCCC;DDDDDD;22222")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.