从 awk 输出构建数组

Building array from awk output

谁能解释一下为什么下面的方法不起作用?

列表

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

script.sh

#!/bin/bash

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

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

如果我 运行 这个 bash script.sh list 我希望数组打印 d 和 g,但它没有。我认为这是因为我尝试设置数组的方式。

I think its because of how I am trying to set the array.

管道 | 中的每个命令在子 shell 中 运行 - 作为一个单独的进程。父进程不会 "see" 从子进程更改变量。

刚刚:

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

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

运行 父变量赋值 shell.

您应该将整行管道命令分配给一个变量。

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

catgrep命令可以和awk结合使用,但是为什么要数组呢?
我想你想在一个循环中处理每个元素,所以首先删除双引号:

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

接下来,尝试在没有数组的情况下执行此操作

while read -r i; do
  :
  echo $i
done < <(awk '/letter/ {print }' "")