3

How can I align data into pretty columns relative to given word?

For example, I have output of the route -n command:

default via 172.20.99.254 dev eth0 
87.33.17.71 dev tun0 scope link 
89.223.15.12 via 172.20.99.254 dev eth0 src 172.20.99.74 
172.20.9.0/24 dev eth0 proto kernel scope link src 172.20.99.74 
65.46.5.89 dev tun0 scope link 
192.168.11.0/24 dev tun0 scope link 
45.211.111.7 dev tun0 scope link 

and I would like to align it by the word dev, so that the column containing the word dev is aligned:

default via 172.20.99.254       dev eth0 
87.33.17.71                     dev tun0 scope link 
89.223.15.12 via 172.20.99.254  dev eth0 src 172.20.99.74 
172.20.9.0/24                   dev eth0 proto kernel scope link src 172.20.99.74 
65.46.5.89                      dev tun0 scope link 
192.168.11.0/24                 dev tun0 scope link 
45.211.111.7                    dev tun0 scope link 

I cannot just naively replace fist space character with a tab, because sometimes I need 1 tab, other times I need 3 tabs.

1 Answer 1

7

I would use a character that I am sure it doesn't exist into file, as a dummy separator for the column command, like:

$ sed 's/dev/@dev/' file | column -ts@
default via 172.20.99.254        dev eth0 
87.33.17.71                      dev tun0 scope link 
89.223.15.12 via 172.20.99.254   dev eth0 src 172.20.99.74 
172.20.9.0/24                    dev eth0 proto kernel scope link src 172.20.99.74 
65.46.5.89                       dev tun0 scope link 
192.168.11.0/24                  dev tun0 scope link 
45.211.111.7                     dev tun0 scope link 

You can also use -o (specify the output separator) together with column, you can try with -o "" or -o " " to see behaviour.

Also the above sed substitutes only the first occurence, and a simple matching was used, maybe you 'd need a more strict matching for other cases, like matching surrounding whitespaces.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.