How to select an element from a 2d array in a file

2019-06-09 02:03发布

I am new to shell scripting and what I need is to read from a file that contains a 2d array. Assume there is a file named test.dat which contains values as:

- Paris         London     Lisbon
- Manchester    Nurnberg   Istanbul
- Stockholm     Kopenhag   Berlin

What is the easiest way to select an element from this table in linux bash scripts? For example, the user inputs -r 2 -c 2 test.dat that implies to selecting the element at row[2] and column[2] (Nurnberg).

I have seen the read command and googled but most of the examples were about 1d array.

This one looks familiar but could not understand it exactly.

1条回答
一夜七次
2楼-- · 2019-06-09 02:34

awk is great for this:

$ awk 'NR==row{print $col}' row=2 col=2 file
Nurnberg
  • NR==row{} means: on number of record number row, do {} Number of record normally is the number of line.
  • {print $col} means: print the field number col.
  • row=2 col=2 is giving both parameters to awk.

Update

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_.

For example:

#!/bin/bash

file=$1
row=$2
col=$3

awk 'NR==row{print $col}' row=$row col=$col $file

And you execute like:

./script a 3 2
Kopenhag
查看更多
登录 后发表回答