[shell] 读取多行输出到数组/遍历awk输出的某一行

效果

想要达到的效果为,使用awk切分输出后,遍历每一行的输出。以下以ls -lh命令示例,遍历输出ls -lh命令的第一列输出。实际使用替换ls -lh

演示

1. 存放到数组后遍历数组

第一种方式, 简约但不推荐 https://github.com/koalaman/shellcheck/wiki/SC2207

array=( $(ls -lh | awk '{print $1}') )

第二种方式, 读取到数组中

array=()
while IFS='' read -r line; do array+=("$line"); done < <(ls -lh | awk '{print $1}')

遍历数组输出

for i in "${array[@]}" ; do
    echo "column:$i"
done

2. 直接遍历每一行的输出

如果读取到数组中最终也是要遍历的话,可以直接遍历输出的行

第一种写法

ls -lh | awk '{print $1}' |
while IFS='' read -r line; do
    echo "column:$line"
done

第二种写法

while IFS='' read -r line; do
    echo "column:$line"
done  < <(ls -lh | awk '{print $1}')
posted @ 2023-03-29 10:03  小小记录本  阅读(855)  评论(0编辑  收藏  举报