我是 shell 脚本的新手,我需要的是从包含二维数组的文件中读取。假设有一个名为 test.dat 的文件,其中包含以下值:
- Paris London Lisbon
- Manchester Nurnberg Istanbul
- Stockholm Kopenhag Berlin
在 linux bash 脚本中从该表中选择元素的最简单方法是什么?例如,用户输入 -r 2 -c 2 test.dat 表示选择 row[2] 和 column[2] (Nurnberg) 处的元素。
我看过读取命令并用谷歌搜索过,但大多数示例都是关于一维数组的。
This一个人看起来很熟悉,但无法确切地理解它。
最佳答案
awk
非常适合这个:
$ awk 'NR==row{print $col}' row=2 col=2 file
Nurnberg
NR==row{}
表示:在第row
个记录数上,执行{}
Number of record 通常是第行。{print $col}
表示:打印字段编号col
。row=2 col=2
将两个参数都提供给awk
。
更新
One more little question: How can I transform this into a sh file so that when I enter -r 2 -c 2 test.dat into prompt, I get to run the script so that it reads from the file and echoes the output? – iso_9001_.
例如:
#!/bin/bash
file=$1
row=$2
col=$3
awk 'NR==row{print $col}' row=$row col=$col $file
然后你像这样执行:
./script a 3 2
Kopenhag
关于arrays - 如何在 Linux shell 中从文件中的二维数组中选择一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21134802/