Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

You can use the variable as the start and end range for the column numbers to be printed. Here's an example:

Suppose you have a file called data.txt with the following contents:

1,2,3,4,5
6,7,8,9,10
11,12,13,14,15

And you want to print columns 2 to 4 (i.e., 2nd, 3rd and 4th columns) using a variable called "cols". Here's how you can do it:

cols="2-4"
awk -F',' "{OFS=\",\"; print \$$cols}" data.txt

In the above command, we are setting the field separator to "," using the "-F" option, and then setting the output field separator to "," using the "OFS" variable. We are then using the "print" command to print the specified columns using the "$cols" variable. Since "$cols" is in the form of "start-end", we can use it directly as a range of columns by prefixing it with "$$" (which allows us to use the variable as a column number).