View Full Version : fun with variables
nickoli
October 19th, 2007, 11:59 PM
I need to write a script to count the number of characters in a variable. I wrote this script test=abc | echo '$test' | wc -c and it keeps coming up with five. I am trying to figure out what I'm missing. The answer should be four. Any help will be appreciated.
Malibu Illusion
October 20th, 2007, 12:18 AM
"" = 1 byte
So:
#!/usr/bin/sh
len=`echo "test" | wc -c`
len=`expr $len - 1`
echo "length = $len"
= 4 and what you want.
ghostdog74
October 20th, 2007, 12:20 AM
use awk instead
#var="test"
# echo $var|awk '{print length}'
nickoli
October 20th, 2007, 12:44 AM
Thanks for your help. Awk was my missing command. I never used awk so far. Is there anyway you can give me a brief description of how it works. I really appreciate your help. Once again thanks.
:popcorn:
ghostdog74
October 20th, 2007, 03:31 AM
this online boo (http://www.unix.org.ua/orelly/unix/sedawk/ch07_01.htm)k explains much better than me
CptPicard
October 20th, 2007, 03:52 AM
I need to write a script to count the number of characters in a variable. I wrote this script test=abc | echo '$test' | wc -c and it keeps coming up with five. I am trying to figure out what I'm missing. The answer should be four. Any help will be appreciated.
Just to note what you're doing wrong with your initial solution. The first obvious problem is with quoting. You are using single quotes which prints the literal $test into stdout, which is five characters, which wc -c counts correctly.
The first pipe also does nothing, and I'm not sure these answers you're getting are actual solutions... let's get this straight, you want to count the characters in the variable name? In that case, a simple echo "varname" | wc -c should suffice...
nickoli
October 20th, 2007, 09:33 AM
I want to count the text that is assigned to the variable. #var="test"
# echo $var|awk '{print length}' appears to be the solution. Example var=abcdefg the answer should be 7. Thanks for the tip on the quotes. We just started working on them. I've yet to get that down to a science. Obviously. :)
nickoli
October 20th, 2007, 09:37 AM
I see a mistake that I had made on my original posting could have lead to misunderstanding. I had typed test=abc and the answer should be 4 where as it should have actually been 3. Sorry for any misunderstanding on that.
vBulletin® v3.8.7, Copyright ©2000-2012, vBulletin Solutions, Inc.