Computing.Net > Forums > Unix > Parse a string

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.

Parse a string

Reply to Message Icon

Name: ohuang
Date: September 5, 2008 at 11:01:01 Pacific
OS: AIX
CPU/Ram: ?
Product: ?
Comment:

Hello,
I am trying to parse a string and assign the result to a variable. For example, I have a variable yymm="0809", I am passing this variable into a script. In the script, I'd like to extract the last two digits (09) of the string and assign it to a variable called "month". How do I do that, I tried awk but I couldn't get it to work.

Thanks.



Sponsored Link
Ads by Google

Response Number 1
Name: nails
Date: September 5, 2008 at 13:00:14 Pacific
Reply:

Probably the most simple way is to use the unix cut command. This gets the last 2 characters of argument 1:


#!/bin/ksh

var=$1
len=${#var} # get the length
if [[ $len < 2 ]]
then
echo "arg 1 needs to be 2 characters"
exit
fi
myvar=$(echo "$var"|cut -c"$((len-1))"-"$len")
echo "$myvar"



0

Response Number 2
Name: ghostdog
Date: September 6, 2008 at 19:01:28 Pacific
Reply:

bash


yymm="0809"
var=${yymm:(-2)}


0

Response Number 3
Name: ohuang
Date: September 8, 2008 at 09:11:56 Pacific
Reply:

Nails,ghostdog -
Thank you for the replies from both of you. I ended up by fixing the awk command I was trying to use and I got it working. Thanks for the hints Nais.;) Here it is:

month=$(echo "$1" |awk '{print substr($1,length($1)-1,length($1))}')

thanks again.


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: Parse a string

parsing a variable to a function www.computing.net/answers/unix/parsing-a-variable-to-a-function-/5613.html

Help parsing a path-filename www.computing.net/answers/unix/help-parsing-a-pathfilename/7407.html

Split a string www.computing.net/answers/unix/split-a-string/8023.html