Reputation: 17411
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
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
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:
Upvotes: 2