1831228 Members
2813 Online
110021 Solutions
New Discussion

Basic Question on WC

 
SOLVED
Go to solution
uform
Frequent Advisor

Basic Question on WC

Prompt>echo 'hello' | wc -c
6
Prompt>echo 'hello' | wc -m
6
Prompt>echo 'test' | wc -m
5
Prompt>echo test | wc -m
5
Prompt>echo test|wc -m
5
Prompt>echo test|wc -C
5

i'm expecting 5 characters for hello and 4 for test !!! what am i missing ?

9 REPLIES 9
melvyn burnard
Honored Contributor

Re: Basic Question on WC

There is the additional carriage return character that gets counted as far as I recall
My house is the bank's, my money the wife's, But my opinions belong to me, not HP!
Peter Godron
Honored Contributor

Re: Basic Question on WC

Hi,
man wc
"A word is a string of characters delimited by spaces, tabs, or newlines."

It the newline char at the end:
echo hello | wc -l
1
James R. Ferguson
Acclaimed Contributor

Re: Basic Question on WC

Hi:

The newline character is counted. You can see visually what Melvyn refers to by doing:

# echo hello|cat -etv

Regards!

...JRF...
A. Clay Stephenson
Acclaimed Contributor

Re: Basic Question on WC

Here is an alternative method:

expr length $(echo "hello")
If it ain't broke, I can fix that.
Peter Nikitka
Honored Contributor
Solution

Re: Basic Question on WC

Hi,

if you just need the length of a string:

a=hello
print ${#a}

No additional newline needs to be considered.

mfG Peter
The Universe is a pretty big place, it's bigger than anything anyone has ever dreamed of before. So if it's just us, seems like an awful waste of space, right? Jodie Foster in "Contact"
uform
Frequent Advisor

Re: Basic Question on WC

ok thanks all.
Jonathan Fife
Honored Contributor

Re: Basic Question on WC

You could also put a \c at the end of the echo to supress the newline:

fifejj:/> echo "test\c" | wc -m
4
fifejj:/> echo "hello\c" | wc -m
5
fifejj:/> mystring=hello
fifejj:/> echo "${mystring}\c" | wc -m
5

Decay is inherent in all compounded things. Strive on with diligence
Sandman!
Honored Contributor

Re: Basic Question on WC

wc is also counting the newline character written as \n...for example:

# echo hello | od -c
# echo test | od -c

cheers!
spex
Honored Contributor

Re: Basic Question on WC

# echo 'hello' | awk '{print length}'
5