I would like to parse the output from df
so I do
arr=( $(df -hPT | awk '{print $1, $2, $3, $5, $6, $7}') )
for f in ${arr[@]}; do echo ${f[*]};sleep 1;done
but I get
Filesystem
Size
Avail
Use%
Mounted
devtmpfs
7.8G
7.8G
0%
/dev
tmpfs
7.8G
7.7G
3%
where I had hoped for
Filesystem Size Avail Use% Mounted
devtmpfs 7.8G 7.8G 0%
/dev tmpfs 7.8G 7.7G 3%
My plan was that $f
would be an array for each line, so I can manipulate each line and printf
the output aferwards.
Question
Any ideas how I can get an array of the awk
output per df
line?
Solution 1st: In single while
loop:
df -hPT | while read first second third fourth fifth sixth seventh
do
echo $first $second $third $fifth $sixth $seventh
sleep 1
done
Solution 2nd: Following single awk
may help you on same.
df -hPT | awk '{print $1, $2, $3, $5, $6, $7;system("sleep 1")}'
在读取时使用...循环
df -hPT | while read line ; do echo "$line" | awk '{print $1, $2, $3, $5, $6, $7}' ;sleep 1 ; done
You can use the bash builtin lines
to store the lines of a file/stream into an array:
mapfile -t lines < <(df -hPT | awk '{print $1, $2, $3, $5, $6, $7}')
for line in "${lines[@]}"; do
manipulate "$line"
done
Need to redirect from the process substitution so we don't introduce any subshells.
You've seen what happens when you fail to quote the variable in the for loop: always quote your variables (unless you know exactly why not).
If you set IFS to \\n like that :
IFS=$'\n' arr=( $(df -hPT | \
awk '{print $1, $2, $3, $5, $6, $7}') )
for f in ${arr[@]}; do
echo ${f[*]}
done
echo "nb elt in arr = ${#arr[@]}"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.