首页 > 解决方案 > 从 awk 输出构建数组

问题描述

谁能解释为什么以下不起作用?

列表

the letter is d
the number is 4
the number is 2
the letter is g

脚本.sh

#!/bin/bash

cat "$1" | grep letter | array=($(awk '{print $4}'))

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

如果我运行它bash script.sh list,我希望数组打印 d 和 g,但事实并非如此。我认为这是因为我试图设置数组。

标签: arrayslinuxbashawkcat

解决方案


我认为这是因为我试图设置数组。

管道中的每个命令|都在子 shell 中运行 - 作为单独的进程。父进程不会“看到”来自子进程的变量更改。

只是:

array=($(grep letter "$1" | awk '{print $4}'))

或者

array=($(awk '/letter/{print $4}' "$1"))

在父 shell 中运行变量赋值。


推荐阅读