Friday, March 21, 2008

Print/Remove first some characters of string


#The string
$ var="unixbashscripting"


#To print the first 8 characters of the string "unixbashscripting"

1)
$ echo ${var:0:8}
unixbash

2)
$ echo $var | sed 's/\(.\{8\}\).*/\1/'
unixbash

3)
$ echo $var | awk '{print substr($0,1,8)}'
unixbash

4)
$ echo $var | cut -c1-8
unixbash

5)
$ printf "%.8s\n" "$var"
unixbash

6)
$ echo "${var%${var#????????}}"
unixbash


#To remove the first 8 characters of the string "unixbashscripting"

1)
$ echo $var | cut -c9-
scripting

2)
$ echo "${var#????????}"
scripting

3)
$ echo ${var:8}
scripting

4)
$ echo $var | awk '{print substr($0,9)}'
scripting

5 comments:

Even God loves a lying sack... said...

Pretty handy, thanks.

stefanos said...

you just saved me hours of tedious file renaming, thanks dude.

Greg Taylor said...

Thankyou very much - i was looking to truncate/remove the middle of really long filenames (90+ chars), and your solution saved me!

To get the, say, the first and last 3 characters:
var=123456789
echo "${var%${var#???}}${var#${var%???}}"

Kindest regards, and thankyou again ;)
greg

Jadu Saikia said...

@stefanos thanks.
@Greg Taylor thanks lot.

Praveen Kumar said...

Hi Greg, Thanks for the tip, is there any way to extract the substring from text like 456 from 123456789 using your approach. Thanks in advance.

© Jadu Saikia www.UNIXCL.com