Text Column Retrieval

Question

I can use Awk to print the nth column from a file. The cut command can do a similar thing. But I want the column to be output based on its name, for example:

 

col1 col2 col3 col4

2 5 3 1

6 4 7 1

3 6 5 9

7 9 7 8

 

If I give a list of column names as input: e.g. col1, col3 (it will be a long list, so it would help if the input could be an array). The output would be:

 

col1 col3

2 3

6 7

3 5

7 7

Does anyone know how I might do this in Bash?

 

Answer

Awk and cut command can handle basic text file processing. But, if the computing target is not very simple, the code will be long and difficult. Try solving the problem in SPL, which enables simple code:

A

1

=file("/data/file.txt").import@t(col1,col3)

 

A1: Import col1 and col3 columns from file.txt.

If you want to perform structured computation after data retrieval, like grouping & aggregation and sorting, see other articles in Q&A for solutions.