0

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 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

9 Comments

Great! I was suspecting awt would work :) Thank you very much
awk is sooooo powerful for this kind of things :) Glad it worked to you!
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?
You are really fast and have been very helpful :) thank you very much
Today, I have successfully managed to write the code as you suggested. So, thanks again. What I now lack is, I can manage to run the code as ./tablooku.sh tablom.dat 2 2 but when I try to parameterize "2 2" part as ./tablooku.sh tablom.dat -r 2 -c 2 I get my error message that says "Error: -rth row and -cth column does not exist". How can I parameterize the command?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.