简体   繁体   English

AWK输出到bash数组

[英]AWK output to bash Array

Im trying to put the contents of a simple command in to a bash array however im having a bit of trouble. 我试图将一个简单的命令的内容放入一个bash数组但是我有点麻烦。

df -h | awk '{ print  $5" "$6 }'

gives percentage used in the file systems on my system output looks like this: 给出我系统输出文件系统中使用的百分比如下所示:

1% /dev
1% /dev/shm
1% /var/run
0% /var/lock
22% /boot
22% /home
22% /home/steve

I would then like to put each of these lines into a bash array array=$(df -h| awk '{ print $5 $6 }') 我想将这些行中的每一行放入一个bash数组中= $(df -h | awk'{print $ 5 $ 6}')

However when I print out the array I get the following: 但是,当我打印出数组时,我得到以下内容:

5%
/
1%
/dev
1%
/dev/shm
1%
/var/run
0%
/var/lock
22%
/boot
22%
/home
22%
/home/steve

Bash is forming the array based on white spaces and not line breaks how can i fix this? Bash基于白色空间而不是换行符形成阵列我该如何解决这个问题呢?

You need to reset the IFS variable (the delimeter used for arrays). 您需要重置IFS变量(用于数组的分隔符)。

OIFS=$IFS #save original
IFS=','
df -h | awk '{ print $5" "$6"," }'

You could do this in Bash without awk. 你可以在没有awk的情况下在Bash中执行此操作。

array=()
while read -a line; do
    array+=("${line[4]} ${line[5]}")
done < <(df -h)

你可以用这个:

eval array=( $(df -h | awk '{ printf("\"%s %s\" ", $5, $6) }') )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM