print last field from line + alternative for awk
12,259
Solution 1
Perl
echo foo bar baz | perl -pe 's/.*[ \t]//'
If you have to strip trailing spaces first, do it like this:
echo "foo bar baz " | perl -lpe 's/\s*$//;s/.*\s//'
The following was contributed by mr.spuratic in a comment:
echo "foo bar baz " | perl -lane 'print $F[-1]'
Bash
echo foo bar baz | while read i; do echo ${i##* }; done
or is bash
is not your default shell:
echo foo bar baz | bash -c 'while read i; do echo ${i##* }; done'
If you have to strip a single trailing space first, do
echo "foo bar baz " | while read i; do i="${i% }"; echo ${i##* }; done
tr and tail
echo foo bar baz | tr ' ' '\n' | tail -n1
although this will only work for a single line of input, in contrast to the solutions above. Suppressing trailing spaces in this approach:
echo "foo bar baz " | tr ' ' '\n' | grep . | tail -n1
Solution 2
Using Cut:
Last field:
echo 1 2 3 4 5 | rev | cut -f1 -d ' '
Last character:
echo 1 2 3 4 5 | rev | cut -c1
Solution 3
echo hello my friend | tac -s' ' | tr '\n' ' ' | cut -d' ' -f 1
Related videos on Youtube
Author by
yael
Updated on September 18, 2022Comments
-
yael over 1 year
Due to technical reason on my Solaris machine, I can't use
awk
in order to print the last field in line.What are the other alternatives to
awk
that print the last field from line (usingcut
ortr
...etc)?Example 1:
/usr/bin/hostname machine1b /usr/bin/hostname | /usr/bin/sed 's/\(.\{1\}\)/\1 /g' | /usr/bin/awk '{print $NF}' b
Example2
echo 1 2 3 4 5 | /usr/bin/awk '{print $NF}' 5
-
Admin about 11 yearsWhat is your goal? Given that
sed
code seem you need the last character, not the last field. To get the hostname's last character inbash
,${HOSTNAME: -1}
may be enough. (Not sure if Solaris sets such variable.) -
Admin about 11 yearsthe sed code only seperate between characters , so I will can to print the last word/character , I still need alternative for awk , because I have other examples in my code ,
-
-
yael about 11 yearsnot work on my solaris machine - echo 1 2 3 4 5 | sed -E -e 's/.* ([^ ]+)$/\1/' sed: illegal option -- E
-
mr.spuratic about 11 yearsTo add to your comprehensive list:
perl -an
allows the use of theF
array like awk's$1
,$2
etc, though it is zero-indexed and there is no specialNF
so you use$F[-1]
(or the slightly unpretty$F[$#F]
). -
Emanuel Berg about 11 yearsYeah, but isn't "field" the entire word or number? Try your command with
51
instead of5
. Check out my answer. -
Skippy le Grand Gourou over 9 yearsJust pipe to
rev
again at the end to reverse back.