4

Lets say I have a word of length N.

word0=`echo` # N = 0  
word1=`echo A` # N = 1
word2=`echo AB` # N = 2
word5=`echo ABCDE` # N = 5
word4=`echo "ABCD"` # N = 4

I use wc to get the length ofwordN, for example:

echo $word0 | wc 
   1 
echo $word1 | wc 
   2 
echo $word4 | wc 
   5

wc adds +1 to the word length and result is N+1

Even with wc -c or wc -m I got N+1

Question: Should wc work like this? If so, why it adds +1?

pogibas
  • 27,303
  • 19
  • 84
  • 117
  • Those are [useless `echo`s](http://www.iki.fi/era/unix/award.html#echo) though; you want simply `word0=''; word1='A'` etc – tripleee Aug 25 '21 at 19:24

2 Answers2

10

try:

echo -n "stuff"|wc

echo adds a newline, so if you count by bytes or chars, there is at least 1

see following examples:

kent$  echo ""|wc -c
1

kent$  echo -n ""|wc -c
0

kent$  echo  ""|wc -m
1

kent$  echo  -n ""|wc -m
0

if you count by "word", there is no difference:

kent$  echo  -n ""|wc -w
0

kent$  echo  ""|wc -w   
0
Kent
  • 189,393
  • 32
  • 233
  • 301
2

My wc prints three values: line count, word count and byte count. I guess yours just prints the byte count. And the echo command you use in the pipe always adds a newline. That's the additional byte you are looking for.

Alfe
  • 56,346
  • 20
  • 107
  • 159