Computing.Net > Forums > Unix > substring function does not work

substring function does not work

Reply to Message Icon

Original Message
Name: pbekal
Date: January 7, 2005 at 08:13:18 Pacific
Subject: substring function does not work
OS: 11.00
CPU/Ram: 1
Comment:

uxwspr60:/home/orcimp> cat test.sh
alpha='abcdefghijklmnopqrstuvwxyz'
print ${alpha:5:5}

uxwspr60:/home/orcimp> test.sh
test.sh[2]: ${alpha:5:5}: The specified substitution is not valid for this command.



Report Offensive Message For Removal


Response Number 1
Name: vgersh99
Date: January 7, 2005 at 10:28:25 Pacific
Reply: (edit)

$ cat test.sh
#!/bin/bash
alpha='abcdefghijklmnopqrstuvwxyz'
echo ${alpha:5:5}


Report Offensive Follow Up For Removal

Response Number 2
Name: Jim Boothe
Date: January 9, 2005 at 09:15:58 Pacific
Reply: (edit)

The bash syntax ${alpha:5:5} will not work on HP-UX.  Following are 4 solutions that will provide the fghij result when $alpha is 10 characters or longer.  But when $alpha is less than 10 characters, they produce different results!

For the sed solution below, if $alpha is less than 10, sed outputs the string as is with no change:

echo $alpha | sed 's/^.....\(.....\).*/\1/'

For expr, if $alpha is less than 10, output will be null:

expr $alpha : ".....\(.....\)"

For the ksh variable manipulations below, if $alpha is less than 10, output will be null:

alpha=abcdefghijklmnopqrstuvwxyz
beyond10=${alpha#??????????}
first10=${alpha%$beyond10}
last5=${first10#?????}
echo $last5

For those same variable manipulations - but nested all together, if $alpha is less than 10, it will still output the shorter-than-5 substring.

echo ${alpha#?????%${alpha#??????????}}


Report Offensive Follow Up For Removal







Use following form to reply to current message:

   Name: From My Computing.Net Settings
 E-Mail: From My Computing.Net Settings

Subject: substring function does not work

Comments:

 


  Homepage URL (*): 
Homepage Title (*): 
         Image URL: 
 
Data Recovery Software




Have you ever used OpenOffice?

Yes, as my main suite.
Yes, occationally.
Yes, but only once.
No, never.


View Results

Poll Finishes In 5 Days.
Discuss in The Lounge