Skip to content
Advertisement

Linux SHELL script, read each row for different number of columns

I have file and for example values in it:

1 value1.1 value1.2
2 value2.1
3 value3.1 value3.2 value3.3

I need to read values using the shell script from it but number of columns in each row is different!!! I know that if for example I want to read second column I will do it like this (for row number as input parameter)

$ awk -v key=1 '$1 == key { print $2 }' input.txt
value1.1

But as I mentioned number of columns is different for each row. How to make this read dynamic?

For example: if input parameter is 1 it means I should read columns from the first row so output should be

value1.1 value1.2

if input parameter is 2 it means I should read columns from the second row so output should be

value2.1

if input parameter is 3 it means I should read columns from the third row so output should be

value3.1 value3.2 value3.2

Th point is that number of columns is not static and I should read columns from that specific row until the end of the row.

Thank you

Advertisement

Answer

Then you can simply say:

awk -v key=1 'NR==key' input.txt

UPDATED

If you want to process with the column data, there will be several ways.
With awk you can say something like:

awk -v key=3 'NR==key {
    for (i=1; i<=NF; i++)
        printf "column %d = %sn", i, $i
}' input.txt

which outputs:

column 1 = value3.1
column 2 = value3.2
column 3 = value3.2

In awk you can access each column value by $1, $2, $3 directly or by $i indirectly where variable i holds either of 1, 2, 3.

If you prefer going with bash, try something like:

line=$(awk -v key=3 'NR==key' input.txt)
set -- $line    # split into columns

for ((i=1; i<=$#; i++)); do
    echo column $i = ${!i}
done

which outputs the same results.
In bash the indirect access is a little bit complex and you need to say ${!i} where i is a variable name.

Hope this helps.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement