Results 1 to 6 of 6
  1. #1
    Join Date
    Jun 2007
    Posts
    11

    Unanswered: command which will print only last character??

    i'm trying to find a command that will print only the last character
    stored in a shell variable.

    i know how to delete the last character:
    sed 's/.$//'

    but when i try to use the a similar command with the reverse outcome:
    sed 's/^[.$]//'

    it does not work.
    any suggestions are appreciated!

  2. #2
    Join Date
    Aug 2006
    Location
    The Netherlands
    Posts
    248
    Code:
    sed 's/^.*\(.\)$/\1/'
    This regular expression uses a substring, between '\(' and '\)', to denote the last single character of the line in the search string. The replace string refers to the (first) substring with '\1' and so replaces the initial string with only the last character.
    Note that
    Code:
    's/^[.$]//'
    means a line with only one or none characters because the '^' used in this way means 'beginning of line'. To reverse a charactermatch use
    Code:
    's/[^.$]//'
    which in this example doesn't do anything because it is searching for something thats not a character and not an 'end of line'.

    Regards
    Last edited by Tyveleyn; 06-02-07 at 05:29.

  3. #3
    Join Date
    Jun 2007
    Posts
    11
    thank you very much...

  4. #4
    Join Date
    May 2007
    Location
    Milano, Italy
    Posts
    22
    Quote Originally Posted by rfourn
    i'm trying to find a command that will print only the last character
    stored in a shell variable
    [...]
    Code:
    $ v="abc"
    $ echo "${v#${v%?}}"
    c

  5. #5
    Join Date
    Jun 2007
    Posts
    11
    based on this answer, how would you go about printing the
    FIRST character??

  6. #6
    Join Date
    May 2007
    Location
    Milano, Italy
    Posts
    22
    Code:
    $ v="abc"
    $ echo "${v%${v#?}}"
    a

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •