Reputation: 31
I want to print my first column and 2nd column from radius.dat and save it to rad.2.out, first column with 3rd column as rad.3.out, and so on.
However, this script doesn't seem to be working.
#!/bin/bash
for i in {2..30}
do
awk '{print $1, $i}' radius.dat > 'rad.'$i'.out'
done
Upvotes: 0
Views: 80
Reputation: 77185
Using awk
you can do:
awk '{for(i=2;i<=NF;i++) print $1, $i > ("rad."i".out")}' radius.dat
The only caveat is that it will lead to many open files, it might not be a problem if you are not on ancient awk
.
What we are doing here is basically using an iterator and iterating through columns starting from the second and printing the first column and the iterator during each iteration to an output file using the naming convention as you desire.
If you notice too many open files
error then you can do:
awk '{
for (i=2; i<=NF; i++) {
print $1, $i >> ("rad."i".out");
close("rad."i".out")
}
}' file
Notice in the second option we use >>
instead of >
. This is due to the fact that we are closing the file after each iteration so we need to make sure we don't overwrite the existing files.
Upvotes: 2
Reputation: 65342
Your quoting is quite off ... awk
never gets the column. Try this:
#!/bin/bash
for i in {2..30}; do
awk "{print \$1, \$$i;}" radius.dat > "rad.$i.out"
done
Upvotes: 0