Pandu
Pandu

Reputation: 1686

Align text by string using shell commands

Say I've got some text in a file like this:

lorem ipsum asdf gh 12345
hello, world! asdf gh this is a test
ee asdf gh ii

Notice that each line contains "asdf gh". I'd like to be able to use some shell command(s) to align that text based on that delimiter string, so I could do:

$ cat my-file | some-command
lorem ipsum     asdf gh   12345
hello, world!   asdf gh   this is a test
ee              asdf gh   ii

In this example I added extra spaces around the delimiter, but it doesn't really matter either way. That is, the output could just as well be:

$ cat my-file | some-command
lorem ipsum   asdf gh 12345
hello, world! asdf gh this is a test
ee            asdf gh ii

Is there a simple way to do this? I know column can columnate things, but it can only use whitespace or characters (not strings or patterns) as delimiters.

Upvotes: 1

Views: 1219

Answers (3)

anubhava
anubhava

Reputation: 785058

awk is a better tool for formatting output:

awk -F 'asdf gh' '{printf "%-15s%-10s%-10s\n", $1, FS, $2}'  file
lorem ipsum    asdf gh    12345    
hello, world!  asdf gh    this is a test
ee             asdf gh    ii    

You can change numbers in printf for more customization.

Upvotes: 6

mockinterface
mockinterface

Reputation: 14860

Unless you want to use awk and have two problems, you could do along the lines of:

sed 's/asdf gh/%&/g' <my-file | column -t -s'%'

assuming that '%' is a valid separator that doesn't otherwise appear in your text.

Upvotes: 1

BMW
BMW

Reputation: 45243

Using printf function in awk

awk '{printf "%-20s%s\t%s\n",$1,FS,$2}' FS="asdf gh" file

lorem ipsum         asdf gh  12345
hello, world!       asdf gh  this is a test
ee                  asdf gh  ii

Upvotes: 3

Related Questions