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
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.
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:
Summary: I was wondering if/how you can parse a variable to a function within a unix script (BASH). What I'm trying to do is print lines from my script to a file a number of times, I'd like to give the functio...
Summary: Thanks, Nails. The filenames I have to parse are actually retrieved from a database call, and are not actual files on the Unix system, so I don't think the basename / dirname will be the solution. I t...
Summary: Hello, I'd like to a split a string into two parts and assign them to two different variables. The string will be passed as an argument to a Korn Shell script For example I have a string something lik...