Shell tricks - Programming On Unix

Users browsing this thread: 3 Guest(s)
josuah
Long time nixers
Alignment with sed

If you ever tried to align the output of a command? column(1) is the tool you need, but it is not in POSIX, and only takes one-character separator, and you might want to only align to the first separator.

A `while read' with printf is a bit cumbersome and slow, let's use the almighty stream editor with two expressions:

Code:
s/SEPARATOR/            /        # replace the SEPARATOR (any sed expression) with enough spaces
    s/(.{12}[^ ]*) */\1SEPARATOR/    # cut excessive spaces up to the 12th column, adding the separator back

To be used this way (but use `column -t -s : /etc/passwd' instead in this case):

Code:
$ sed -r -e 's/:/            /' -e 's/(.{12}[^ ]*) */\1 /' /etc/passwd
...
_slaacd     :*:115:115:SLAAC Daemon:/var/empty:/sbin/nologin
nobody      :*:32767:32767:Unprivileged user:/nonexistent:/sbin/nologin
josuah      :*:1000:1000:Josuah:/home:/bin/sh
_rsync      :*:669:669:rsync Daemon:/var/empty:/sbin/nologin
_gitdaemon  :*:778:778:GIT Daemon:/nonexistent:/sbin/nologin
...

There are a few caveats: if a long input contains spaces before the separator:

Code:
$ printf 'w w w w w w w w w w w w:<- separator\n' | sed -r -e 's/:/            /' -e 's/(.{12}[^ ]*) */\1:/'
w w w w w w w:w w w w w            <- separator

But for known inputs, it works ok.

[edit]: typo


Messages In This Thread
Shell tricks - by josuah - 13-11-2017, 05:27 AM
RE: Shell tricks - by josuah - 13-11-2017, 05:39 AM
RE: Shell tricks - by venam - 14-11-2017, 01:53 AM
RE: Shell tricks - by josuah - 23-11-2017, 07:59 AM
RE: Shell tricks - by josuah - 23-11-2017, 08:52 AM
RE: Shell tricks - by josuah - 04-12-2017, 07:43 AM
RE: Shell tricks - by z3bra - 04-12-2017, 08:11 PM
RE: Shell tricks - by josuah - 05-12-2017, 08:07 AM
RE: Shell tricks - by josuah - 05-12-2017, 09:02 AM
RE: Shell tricks - by josuah - 05-12-2017, 09:08 AM
RE: Shell tricks - by josuah - 08-12-2017, 12:25 PM