extract string
Kevin D. Clark
kevin_d_clark at comcast.net
Tue Jan 10 17:05:01 EST 2006
Ben Scott writes:
> Is there a tool that quickly and easily extracts one or more columns
> of text (separated by whitespace) from an output stream? I'm familiar
> with the
>
> awk '{ print $3 }'
>
> mechanism, but I've always felt that was clumsy. I've tried to get
> cut(1) to do it in the past, but the field separator semantics appear
> to assume one and only one separator, not "whitespace" (one or more
> space or tab characters).
>
> I get the feeling there is some command or switch I'm not aware of
> that I should be using. This hyptherical command might work something
> like this:
>
> ls -l | foo 3
>
> to extract just the third column (username) from the ls(1) output.
Thoughts:
0: I've always found awk and cut to be very convenient for these
operations. For complex things, I recommend Perl. In particular,
awk and Perl allow for pattern separators, as you desire.
1: You might find awk's -F option to be useful.
2: Something like this is always fun:
perl -F: -ane 'print join " ", @F[0,5,6]' /etc/passwd
3: If you really want foo, how about this:
foo() {
if [ $# -eq 0 ] ; then
foo 0
else
awk "{ print `echo "${@}" | sed 's/\([0-9]*\)/\\$\1/g'` }"
fi
}
I leave it to the reader to improve this if so desired. (-:
Hope this helps,
--kevin
--
(There are also also 228 babies named Unique during the 1990s alone,
and 1 each of Uneekm, Uneque, and Uneqqee.)
-- _Freakonomics_, Steven D. Levitt and Stephen J. Dubner
More information about the gnhlug-discuss
mailing list