AWK 输出到 bash 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4056250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 22:50:30  来源:igfitidea点击:

AWK output to bash Array

arraysbashawk

提问by Brian Clements

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  " " }'

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 数组 array=$(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 是基于空格而不是换行符来形成数组,我该如何解决这个问题?

回答by Brian Clements

You need to reset the IFS variable (the delimeter used for arrays).

您需要重置 IFS 变量(用于数组的分隔符)。

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

回答by ephemient

You could do this in Bash without awk.

你可以在没有 awk 的情况下在 Bash 中做到这一点。

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

回答by Diego Torres Milano

You may use this:

你可以使用这个:

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