Select the last two characters from a line of output

Code junkies hangout here

Moderators: ChrisThornett, LXF moderators

Select the last two characters from a line of output

Postby pc » Wed Feb 01, 2006 10:13 pm

I was hoping, using a simple pipe and unix command, to be able to cut the last two characters off a line.

example output: 178256
required output: 56

I thought of using the cut command, but can only seem to specify characters from the start of the line. The line is not always the same number of characters.

echo 178256 | cut -c5-
will give 56
as will
echo 178256 | cut -c5-6

but will be incorrect if the say the number was 1785656.

Any suggestions welcome. I am sure there must be a way, there usually is, without having to write a script.
pc
 
Posts: 24
Joined: Fri Apr 08, 2005 5:12 pm

RE: Select the last two characters from a line of output

Postby Nigel » Wed Feb 01, 2006 11:18 pm

Try this...

Code: Select all
echo 178256 | tail -c -3
echo 1785656 | tail -c -3


My experiments suggest that -3 is needed to get the last 2 digits rather than -2; at first I thought it was due to the space before the pipe, but it needs it even without the space there. Perhaps it's the End-Of-Data marker ?
Hope this helps,

Nigel.
User avatar
Nigel
LXF regular
 
Posts: 1141
Joined: Fri Apr 08, 2005 8:03 pm
Location: Gloucestershire, UK

Postby pc » Thu Feb 02, 2006 7:47 pm

Thanks very much it did the trick. Tried it on both on Redhat and Solaris.

As a point of interest, looking at the tail help, I didn't see why you used the "-" in the "-3". Tried it without, ie:

echo 178256 | tail -c 3
echo 1785656 | tail -c 3

and it worked exactly the same.

Thank-you for you help.
pc
 
Posts: 24
Joined: Fri Apr 08, 2005 5:12 pm

Postby Nigel » Thu Feb 02, 2006 8:47 pm

According to the man page for tail, the - before the number is optional ; either will count from the end of the input. If you use + instead it will count from the beginning of the input. I tend to put optional things like that in when I'm writing scripts just to make it really obvious what I mean when I come back to it months or years later ;)

Oh, and it works on OS X as well, in case you care...
User avatar
Nigel
LXF regular
 
Posts: 1141
Joined: Fri Apr 08, 2005 8:03 pm
Location: Gloucestershire, UK


Return to Programming

Who is online

Users browsing this forum: Yahoo [Bot] and 2 guests