3

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
2
  • 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.)
    – manatwork
    Apr 2, 2013 at 9:10
  • 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
    Apr 2, 2013 at 9:17

4 Answers 4

6

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
1
  • 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]). Apr 2, 2013 at 10:07
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
2
  • Yeah, but isn't "field" the entire word or number? Try your command with 51 instead of 5. Check out my answer. Apr 2, 2013 at 15:20
  • Just pipe to rev again at the end to reverse back. Nov 25, 2014 at 17:05
2

echo hello my friend | tac -s' ' | tr '\n' ' ' | cut -d' ' -f 1

0

Something like this should work:

sed -E -e 's/.* ([^ ]+)$/\1/'

% echo 1 2 3 4 5 | sed -E -e 's/.* ([^ ]+)$/\1/'
5
2
  • not work on my solaris machine - echo 1 2 3 4 5 | sed -E -e 's/.* ([^ ]+)$/\1/' sed: illegal option -- E
    – yael
    Apr 2, 2013 at 9:27
  • try something like this: sed -e 's/.* \([^ ]\{1,\}\)/\1/' Sorry, I don't have any Solaris machine to actually test it.
    – gelraen
    Apr 2, 2013 at 9:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .