awk:将整行(带空格的字符串)打印到BASH数组中

时间:2014-07-21 11:10:49

标签: arrays bash awk text-processing

$ cat / proc / asound / cards

 0 [MID            ]: HDA-Intel - HDA Intel MID
                      HDA Intel MID at 0xb0610000 irq 64
 1 [PCH            ]: HDA-Intel - HDA Intel PCH
                      HDA Intel PCH at 0xb0614000 irq 65

我试图将每个条目的第二行保存到BASH数组中:

eval sound_card_array=($(awk 'NR%2==0' /proc/asound/cards)) #also tried without eval -> same result

#echo $(awk 'NR%2==0' /proc/asound/cards) --> this produces the proper output of each line

应该是这样的:

["HDA Intel MID at 0xb0610000 irq 64", "HDA Intel PCH at 0xb0614000 irq 65"]

相反,当我打印出sound_card_array时,我只获得部分字符串,或者我将它们全部放在不同的数组元素中。我试过在awk调用周围添加引号,添加echo,在访问数组时在变量周围加上引号(即“$ {sound_card_array [$ i]}”),但都没有工作。

更新:谢谢你们。也许我的问题也与我访问数组的方式有关:

for sc in "${!sound_card_array[@]}"
do
        if [ "$sc" -lt "$((${#sound_card_array[@]}-1))" ]; then
                j_pair $sc "${sound_card_array[$i]}"
        else
                j_pair_last $sc "${sound_card_array[$i]}"
        fi

done

其中j_pair和j_pair_last是我写的BASH函数,它接受两个参数并将它们回显到一个文件:

function j_pair {
        printTabs
        echo  "\"$1\":\"$2\","
}
function j_pair_last {
        printTabs
        echo  "\"$1\":\"$2\""
}

我是BASH的新手,所以我确信有很多事情我可能做错了。再次感谢您的帮助!

对于awk和printf:

$ arr=($(awk 'NR%2==0{$1=$1; print}' /proc/asound/cards))
$ printf "%s\n" "${arr[@]}"

HDA
Intel
MID
at
0xb0610000
irq
64
HDA
Intel
PCH
at
0xb0614000
irq
65

3 个答案:

答案 0 :(得分:2)

问题在于您使用eval

您不需要(也不得)使用eval从BASH中的awk输出创建数组。将IFS分配给数组时使用IFS=$'\n' arr=($(awk 'NR%2==0{$1=$1; print}' /proc/asound/cards))

$1=$1

PS:我使用printf "%s\n" "${arr[@]}" HDA Intel MID at 0xb0610000 irq 64 HDA Intel PCH at 0xb0614000 irq 65 进行awk重新格式化并删除第二行中的所有前导空格。

然后测试:

{{1}}

答案 1 :(得分:1)

刚刚使用Bash:

sound_card_array=() i=0
while IFS= read -r line; do
    (( i++ % 2 )) && sound_card_array+=("${line:22}")
done < /proc/asound/cards

测试:

sound_card_array=() i=0
while IFS= read -r line; do
    (( i++ % 2 )) && sound_card_array+=("${line:22}")
done < sample.txt
printf '%s\n' "${sound_card_array[@]}"

输出:

HDA Intel MID at 0xb0610000 irq 64
HDA Intel PCH at 0xb0614000 irq 65

答案 2 :(得分:1)

我可以看到两个选项:

如果单词的数量是常数:

sound_card_array=($(awk 'NR%2==0' cards ))

echo ${sound_card_array[@]:0:7}
HDA Intel MID at 0xb0610000 irq 64

echo ${sound_card_array[@]:7:7}
HDA Intel PCH at 0xb0614000 irq 65

或者:

sound_card_array=($(awk 'NR%2==0{$1=$1;a=$0; gsub(" +","_",a); print a}' cards ))

echo ${sound_card_array[0]} | tr "_" " "
HDA Intel MID at 0xb0610000 irq 64

echo ${sound_card_array[1]} | tr "_" " "
HDA Intel PCH at 0xb0614000 irq 65

希望这有帮助