[英]Building array from awk output
Can anyone explain why the following doesn't work please?谁能解释为什么以下不起作用?
list列表
the letter is d
the number is 4
the number is 2
the letter is g
script.sh脚本文件
#!/bin/bash
cat "$1" | grep letter | array=($(awk '{print $4}'))
for i in "${array[@]}"
do
:
echo $i
done
If I run this bash script.sh list
I expect the array to print d and g, but it doesn't.如果我运行这个
bash script.sh list
我希望数组打印 d 和 g,但它没有。 I think its because of how I am trying to set the array.我认为这是因为我试图设置数组。
I think its because of how I am trying to set the array.
我认为这是因为我试图设置数组。
Each command in a pipeline |
管道中的每个命令
|
is run in a subshell - as a separate process.在子shell中运行 - 作为一个单独的进程。 The parent process does not "see" variable changes from a child process.
父进程不会“看到”子进程的变量变化。
Just:只是:
array=($(grep letter "$1" | awk '{print $4}'))
or或者
array=($(awk '/letter/{print $4}' "$1"))
Run variable assignment in the parent shell.在父 shell 中运行变量赋值。
You should assign the complete row of piped commands to a variable.您应该将完整的管道命令行分配给一个变量。
array=($(cat "$1" | grep letter | awk '{print $4}'))
The cat
and grep
command can be combined with awk
, but why do you want an array? cat
和grep
命令可以与awk
结合使用,但为什么要数组呢?
I think you want the process each element in one loop, so first remove the double quotes:我认为您希望在一个循环中处理每个元素,因此首先删除双引号:
for i in ${array[@]}
do
:
echo $i
done
Next, try to do this without an array接下来,尝试在没有数组的情况下执行此操作
while read -r i; do
:
echo $i
done < <(awk '/letter/ {print $4}' "$1")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.