Ask Your Question
0

How can you print a range of columns in awk using a variable?

asked 2022-12-09 11:00:00 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-01-20 10:00:00 +0000

nofretete gravatar image

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).

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-12-09 11:00:00 +0000

Seen: 8 times

Last updated: Jan 20 '22