Kashyap
Kashyap

Reputation: 17411

Command to print specific column from input

I was wondering if there is some built-in otherwise command available that can print Nth column from input. E.g. awk '{print $2}' or cut...

It would make life easier when I want to run it on piped output while running it via ssh (quoting it always a hell), and of course it'll make life easier in general.

My current hack with a 100 limitations is:

function _printcol(){
    while read data; do
        [ -z "$fields" ] && fields=`for num in "$@"; do echo -n "\"\t\",\\$$num"; done`
        echo $data | awk "{ print $fields }"
    done
}
alias printcol=_printcol
ls -ltr | printcol 9
ls -ltr | printcol 1 9

I'm wondering if someone already implemented it. I would prefer if it's built-in, or available as widely as possible (like on multiple stock distros) or in the worst case easily installable (like yum, apt, ...).

Upvotes: 0

Views: 393

Answers (2)

John1024
John1024

Reputation: 113834

You wanted something easy to install. Just place the following line in your ~/.bashrc file:

 printcol() { fields=$(printf '$%i,' "$@"); awk -v OFS='\t' "{ print ${fields%%,} }"; }

Invoke it just as you were doing:

ls -ltr | printcol 1 9

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 246799

a rewrite

printcol() {
    awk -v "fields=$*" '
        BEGIN { n = split(fields, f) }
        {
            for (i=1; i<=n; i++) {
                printf "%s%s", $(f[i]), OFS
            }
            print ""
        }
    '
}

seq 50 | pr -T5 | printcol 2 4 5

Notes:

  • awk will read the function's stdin: you don't have to capture it and feed it into awk -- advantage: only a single awk invocation, not one per line.
  • you don't need to do any gross pre-processing of the field list. Particularly, why are you doing this inside the while-loop?
  • why are you using a function and an alias?

Upvotes: 2

Related Questions