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

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

substring function does not work

Reply to Message Icon

Name: pbekal
Date: January 7, 2005 at 08:13:18 Pacific
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.




Sponsored Link
Ads by Google

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

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


0

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

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#??????????}}


0

Sponsored Link
Ads by Google
Reply to Message Icon

Related Posts

See More







Post Locked

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.


Go to Unix Forum Home


Sponsored links

Ads by Google


Results for: substring function does not work

Assign to a Variable www.computing.net/answers/unix/assign-to-a-variable/4408.html

How to use substr function in sh www.computing.net/answers/unix/how-to-use-substr-function-in-sh/6654.html

mouse doesn't work under Freebsd 4. www.computing.net/answers/unix/mouse-doesnt-work-under-freebsd-4/3965.html