Wednesday, August 21, 2013

How to print or trim end characters of a string/line in UNIX

The commands below help in printing end characters of a line or a string. I assume that ORACLE_SID is set to "TESTDB" for examples below.

Print last one character from ORACLE_SID: 

$ echo $ORACLE_SID | sed -e "s/^.*\(.\)$/1/"
Output: B

Print last two characters:
$ echo $ORACLE_SID | sed -e "s/^.*\(..\)$/1/"
Output: DB

Print last three characters:
$ echo $ORACLE_SID | sed -e "s/^.*\(...\)$/1/"
Output: TDB

The commands below help in trimming end characters of a line or a string.  I assume that ORACLE_SID is set to "TESTDB" for examples below.

Trims last one character:
$ echo $ORACLE_SID | sed 's/.$//'
Output: TESTD

Trims last two characters:
$ echo $ORACLE_SID | sed 's/..$//'
Output: TEST

Trims last three characters:
$ echo $ORACLE_SID | sed 's/...$//'
Output: TES

No comments: