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

6 comments:

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

Pretty handy, thanks.

stefanos said...

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

Unknown 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

Unknown said...

@stefanos thanks.
@Greg Taylor thanks lot.

Unknown 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.

Unknown said...

Yet more ways to accomplish the task at hand:


var='unixbashscripting'
k=${1:-3} # default value is 3. Note: $k should be an integer > 0.


## Bash
set X; shift
while case $var in '' ) break;; esac
do
case $# in "$k" ) break;; esac
set X ${1+"$@"} "`expr \"X$var\" \: 'X\(.\)'`"; shift
var=`expr "X$var" \: 'X.\(.*\)'`
done
printf '%b' "$@" "\n" #<<<<<<<< use this to print first $k chars
#printf '%s\n' "$var" #<<<<<<<< use this to drop the first $k chars


## Perl
printf '%s\n' "$var" |
perl -sple '
($_) = /^.{$k}/ ? /^.{$k}/g :($_); #<<<< use this to print the first $k
#($_) = /^.{$k}/ ? /(?<=.{$k})(.*)/g :(""); #<<<< use this to drop the first $k
' -- -k="$k"


## Perl
printf '%s\n' "$var" |
perl -sple '
$_ = substr $_, 0, $k; #<<<< use this to print the first $k chars
#substr($_, 0, $k)= ""; #<<<< use this to drop the first $k chars
' -- -k="$k"


## Sed
printf '%s\n' "$var" |
sed -ne "
s/./&\n/$k;/\n/P;t;p ;#<<<< use this to print the first \$k chars
#s/./&\n/$k;s/.*\n//p ;#<<<< use this to drop the first \$k chars
"


## Expr
dots=`csh -c "repeat $k echo -n '.'"`
expr "X$var" \: "X\($dots\)" \| "$var" #<<< use this to print first $k chars
#expr "X$var" \: "X$dots\(.*\)" #<<< use this to drop first $k chars


## Dc
Astr=
while case $var in '' ) break;; esac
do
c=`expr "X$var" : 'X\(.\)'`
var=`expr "X$var" : 'X.\(.*\)'`
Astr=$Astr`printf '%03d' "'$c"`
done
dc -e "
[[]pq]sq
[Zd!= ]sD
[lDx0]sZ
[d1000%SM 1000/d 0Z 10r^/d #<< use this to print the first \$k chars
#Z$k 3*-d 0>Z 10r^%d #<< use this to drop the first \$k chars
0sM lax lbx
"

© Jadu Saikia www.UNIXCL.com