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

Share:
12,259

Related videos on Youtube

yael
Author by

yael

Updated on September 18, 2022

Comments

  • yael
    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 (using cut or tr ...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
      Admin about 11 years
      What is your goal? Given that sed code seem you need the last character, not the last field. To get the hostname's last character in bash, ${HOSTNAME: -1} may be enough. (Not sure if Solaris sets such variable.)
    • Admin
      Admin about 11 years
      the 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
    yael about 11 years
    not work on my solaris machine - echo 1 2 3 4 5 | sed -E -e 's/.* ([^ ]+)$/\1/' sed: illegal option -- E
  • mr.spuratic
    mr.spuratic about 11 years
    To add to your comprehensive list: perl -an allows the use of the F array like awk's $1, $2 etc, though it is zero-indexed and there is no special NF so you use $F[-1] (or the slightly unpretty $F[$#F]).
  • Emanuel Berg
    Emanuel Berg about 11 years
    Yeah, but isn't "field" the entire word or number? Try your command with 51 instead of 5. Check out my answer.
  • Skippy le Grand Gourou
    Skippy le Grand Gourou over 9 years
    Just pipe to rev again at the end to reverse back.