Search code examples
linuxbashgrepcommand-line-interfacewc

Is something wrong with my use of wc or grep in the linux command line? I"m getting +1 on my char count


When I run

echo "obase=2;3" | bc | grep -v \n\s | wc -m

bash returns 3. But when I run

echo "obase=2;3" | bc

bash returns 11.

Why is wc -m one digit high on its count?


Solution

  • The extra character is the trailing newline.

    wc -m receives and counts the following three characters: 1 1 \n.

    $ echo "obase=2;3" | bc | grep -v \n\s | od -c
    0000000    1   1  \n                                                    
    0000003
    

    If you get rid of the newline, the count will be as you're expecting:

    $ echo "obase=2;3" | bc | grep -v \n\s | tr -d '\n' | wc -m
           2