| View previous topic :: View next topic |
| Author |
Message |
pc
Joined: Fri Apr 08, 2005 6:12 pm Posts: 24
|
Posted: Wed Feb 01, 2006 10:13 pm Post subject: Select the last two characters from a line of output |
|
|
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. |
|
| Back to top |
|
 |
Nigel LXF regular

Joined: Fri Apr 08, 2005 9:03 pm Posts: 1141 Location: Gloucestershire, UK
|
Posted: Wed Feb 01, 2006 11:18 pm Post subject: RE: Select the last two characters from a line of output |
|
|
Try this...
| Code: | 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. |
|
| Back to top |
|
 |
pc
Joined: Fri Apr 08, 2005 6:12 pm Posts: 24
|
Posted: Thu Feb 02, 2006 7:47 pm Post subject: |
|
|
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. |
|
| Back to top |
|
 |
Nigel LXF regular

Joined: Fri Apr 08, 2005 9:03 pm Posts: 1141 Location: Gloucestershire, UK
|
Posted: Thu Feb 02, 2006 8:47 pm Post subject: |
|
|
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... |
|
| Back to top |
|
 |
| View previous topic :: View next topic |
|