arrays - 如何在 Linux shell 中从文件中的二维数组中选择一个元素

标签 arrays linux bash shell

我是 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/

相关文章:

linux - tensorflow 和 openSUSE

linux - BASH:如果目录中的文件数为 2 或更多,则需要运行 if 语句

regex - 如何获取使用 bash 构建正则表达式的 TLD 列表?

c++ - 深拷贝int数组c++

java - 递归调用溢出堆栈

用于检查进程是否在 Linux 中挂起的 Python 守护进程

linux - 如何在 debian/linux 上的 Asp.Net Core 2 上使用证书保护数据保护 key 文件

c - 将数据发送到等待 ppoll 的另一个进程的 stdin

javascript - 通过 AJAX 从 JSON 编码获取数组

JQuery:使用两个数组创建链接列表