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).
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
Asked: 2022-12-09 11:00:00 +0000
Seen: 8 times
Last updated: Jan 20 '22
How can I only get the Column with the Filename from a ls -all output with Awk?
How can the number of backslashes be doubled using various versions of `awk`?
Why is awk -i inplace not functioning properly when used within a script?
How can a customized trigger be established for RabbitMQ queues in Zabbix?
Can you extract certain values located between columns in two separate csv files using Grep?
What is the Grep command that can be used to extract a section of the last line?
How can we use Bash to identify the directory that has been around the longest?
How can a decimal output be used in an if-else statement with an awk condition?