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 integer variable and count ea
Name: thoppz Date: December 2, 2004 at 15:01:01 Pacific OS: HP:UX CPU/Ram: 1
Comment:
I've a variable inum= 14232232345 I need to parse the variable so I can count 1+4+2+3+2.........= 45
Name: nails Date: December 2, 2004 at 21:08:52 Pacific
Reply:
Hi:
I think you're asking to parse and add each character. If so, isn't the string above actually equal 31 and not 45?
Here's a ksh method:
#!/bin/ksh
i=0 d="14232232345"
while [ ! -z $d ] do x=$(echo "$d"|cut -c1 ) ((i=$i+$x)) d=$(echo ${d##?} ) # keep removing first char done echo $i
0
Response Number 2
Name: Jim Boothe Date: December 3, 2004 at 08:49:51 Pacific
Reply:
And here's a one-line solution:
expr $(echo 14232232345|sed 's/\(.\)/\1 + /g')0
0
Response Number 3
Name: nails Date: December 3, 2004 at 09:48:20 Pacific
Reply:
Jim:
That's an excellent solution - especially if I understood what you were doing.
Would you mind explaining it, please.
Nails
0
Response Number 4
Name: Jim Boothe Date: December 3, 2004 at 11:46:22 Pacific
Reply:
Sorry 'bout that ...
I use sed to change each character to that character followed by space and +, which gives you
1 + 4 + 2 + ...
because expr requires all operands to be space delimited.
0
Response Number 5
Name: nails Date: December 4, 2004 at 16:34:08 Pacific
Reply:
Jim:
I get it: the \( and \) saves any match - a single character in this case, and then uses the back reference, \1, to print the match plus adding a plus sign:
sed 's/\(.\)/\1 + /g'
Then you add a "0" to properly terminate an arithmetic statment before using the result as a parameter to the expr command. Very COOL!
With ksh, you can make a slight mod and assign the result to a variable using eval:
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: $# gives the number of command-line arguments ($1, $2, $3 etc). For example if you run: myscript banana piano 42 then within the script, $0 = /some/path/myscript $1 = "banana" $2 = "piano" $3 = "42" $...