Accessing the Value of a Variable
My issue came up because I was trying sort and put into columns the output of a command.
The output had tabs to separate the columns and spaces in the name. How do I separate into columns by tabs but not spaces?
Example data: Spaces in Name, Tabs separate fields.
file name is data.txt
Client Name1 10.2.0.0/16 Client 10.100.0.0/16 Client Name2 10.99.0.0/24 Name3 10.100.1.0/24 Name4 10.10.0.0/24 Name 5 10.100.0.0/16 Name 6 172.29.0.0/16
Task: Sort on the number of the output and put into readable columns
Sorting on the second column does not sort on the numbers because of the space in the name
$ cat data.txt | sort -k2 Client 10.100.0.0/16 Name4 10.10.0.0/24 Name3 10.100.1.0/24 Name 5 10.100.0.0/16 Name 6 172.29.0.0/16 Client Name1 10.2.0.0/16 Client Name2 10.99.0.0/24
Lets try assign the delimiter to a tab ‘\t’
$ cat data.txt | sort -t \t -k2 Name3 10.100.1.0/24 Name4 10.10.0.0/24 Name 5 10.100.0.0/16 Name 6 172.29.0.0/16 Client 10.100.0.0/16 Client Name1 10.2.0.0/16 Client Name2 10.99.0.0/24
Still not the outcome we want. Now lets assign the tab character to a variable and access it.
$ cat data.txt | sort -t $'\t' -k2 Client 10.100.0.0/16 Name 5 10.100.0.0/16 Name4 10.10.0.0/24 Name3 10.100.1.0/24 Client Name1 10.2.0.0/16 Client Name2 10.99.0.0/24 Name 6 172.29.0.0/16
As we see, we now have the sort done the way we want. We can now pretty it up with column.
$ cat data.txt | sort -t $'\t' -k2 | column -t Client 10.100.0.0/16 Name 5 10.100.0.0/16 Name4 10.10.0.0/24 Name3 10.100.1.0/24 Client Name1 10.2.0.0/16 Client Name2 10.99.0.0/24 Name 6 172.29.0.0/16
Again, we cannot use the tab as a delimiter unless we assign it a variable and access it.
$ cat data.txt | sort -t $'\t' -k2 | column -t -s $'\t' Client 10.100.0.0/16 Name 5 10.100.0.0/16 Name4 10.10.0.0/24 Name3 10.100.1.0/24 Client Name1 10.2.0.0/16 Client Name2 10.99.0.0/24 Name 6 172.29.0.0/16
Now we have the output we wanted.
The dollar sign in bash outputs the value of the variable.

