Search code examples
unixawkwc

print in awk is removing the spaces while printing


I am trying to print the values with awk , but it is modifying the result by removing the spaces in between fields. I am not getting how to maintain the spaces between fields.

echo "First Names       City     Names     ES"|awk '{$1=$2=$NF="";print $0}'|wc -c

the above statement while printing is removing the spaces between "City" and "Names" as a result the value of wc -c is getting impacted.

Please suggest how to maintain the spaces. My goal is to validate the length of the "City Names" value

I have one more doubt about wc -c output , it always gives 1+ to actual value i.e. if length is 11 it is giving 12.


Solution

  • Please suggest how to maintain the spaces.

    Use a field separator:

    $ echo "First Names       City     Names     ES"|awk -F'[ ]' '{$1=$2=$NF="";print $0}'
            City     Names     
    

    I have one more doubt about wc -c output , it always gives 1+ to actual value

    That's because of the newline. Instead of echo, you can say echo -n so as to disable the trailing newline.

    $ echo | wc -c
    1
    $ echo -n | wc -c
    0