重击:将带引号的字符串拆分为数组 [英] Bash: Split quoted string into array

查看:60
本文介绍了重击:将带引号的字符串拆分为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

data.in :

a b c 'd e'

script.sh :

while read -a arr; do
    echo "${#arr[@]}"
    for i in "${arr[@]}"; do
        echo "$i"
    done
done

命令:

cat data.in | bash script.sh

输出:

5
a
b
c
'd
e'


问题:

如何将'd e'作为数组中的单个元素获取?

How can I get 'd e' as a single element in the array?

更新.这是我到目前为止所做的最好的事情:

Update. This is the best I've done so far:

while read line; do
    arr=()
    while read word; do
        arr+=("$word")
    done < <(echo "$line" | xargs -n 1)
    echo "${#arr[@]}"
    for i in "${arr[@]}"; do
        echo "$i"
    done
done

输出:

4
a
b
c
d e

但是,以下 data.in :

"a\"b" c

会使它失败(以及到目前为止我发现的所有其他脚本,即使在

will fail it (and any other script I have found so far, even in the dup question):

xargs: unmatched double quote; by default quotes are special to xargs unless you use the -0 option

但是此输入是合法的,因为您可以在命令行中输入

But this input is legal because you can type in command line:

echo "a\"b" c

它运行良好.因此,这是行为上的不匹配,而不是非法输入.

And it runs well. So this is a mismatch in behavior not illegal input.

推荐答案

$ eval "a=($(cat data.in))"
$ for i in "${a[@]}";do echo "|$i|";done
|a|
|b|
|c|
|d e|
$

这篇关于重击:将带引号的字符串拆分为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆