user2118994
user2118994

Reputation: 9

Add columns to a field in shell script

How can I add 6 more single space separated columns to a file.

The input file that looks like this:

-11.160574
...
-11.549076
-12.020907
...
-12.126601
...
-11.93235
...
-8.297653  

Where ... represents 50 more lines of numbers.

The output I want is this:

-11.160574 1  1  1 1 1 14
...
-11.549076 51 51 1 1 1 14
-12.020907 1  1  2 2 1 14
...
-12.126601 51 51 2 2 1 14
...
-11.93235 1  1  51 51 1 14
...
-8.297653  51 51 51 51 1 14

The 2nd and 3rd columns are loops for 1 to 51.

The 4th and 5th columns are also loops for 1 to 51, but at the upper level from above.

The last two ones constants columns of 1 and 14.

Upvotes: 0

Views: 417

Answers (2)

John Zwinck
John Zwinck

Reputation: 249093

Here you go, an awk script:

{
    mod = 51
    a = (NR - 1) % mod + 1
    b = int((NR - 1) / mod) + 1
    c = 1
    d = 14
    print $0,a,a,b,b,c,d
}

Run it with something like awk -f the-script.awk in-file.txt. Or make it executable and add #!/usr/bin/awk -f at the top, and you can run it directly without typing awk -f.

Upvotes: 2

dogbane
dogbane

Reputation: 274522

Use a loop to read the file line-by-line and maintain counters to keep track of the field numbers as shown below:

#!/bin/bash
field1=1
field2=1
while read line
do
    echo "$line $field1 $field1 $field2 $field2 1 14"
    (( field1++ ))
    if (( $field1 == 52 )); then
        field1=1
        (( field2++ ))
    fi
done < file

Upvotes: 1

Related Questions