arrays - 从 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,但事实并非如此。我认为这是因为我试图设置数组。
解决方案
我认为这是因为我试图设置数组。
管道中的每个命令|
都在子 shell 中运行 - 作为单独的进程。父进程不会“看到”来自子进程的变量更改。
只是:
array=($(grep letter "$1" | awk '{print $4}'))
或者
array=($(awk '/letter/{print $4}' "$1"))
在父 shell 中运行变量赋值。
推荐阅读
- android - Admob 未批准审核请求
- css - 从 chart.js 调整饼图大小
- algorithm - 查找递归调用在 for 循环中的函数的时间复杂度
- python-3.x - 如何使用 TFIDF 创建嵌入矩阵?
- visual-studio-code - 在扩展的任务中调用用户定义的输入
- sql - 使用多个表并以 ID 引用的 SQL 模式名称
- sql - Oracle SQL 列表间隔
- go - 使用 sqlmock 进行单元测试时在 INSERT 上出现错误“不期望查询”
- node.js - 在 hyperleger 结构中向一个组织管理员发送消息给另一个组织管理员
- reactjs - 使用 Redux Hooks 而不是 connect() 好的设计吗?