Search code examples
bashshellunixquoting

When reading a line using While loop in bash, it's squezzing multiple space into one


I am writing a shell Script to read the number of blank space into a file.

I am using following template to read line one by one

 while read l 
 do

 done <filename

but It's converting multiple spaces into one space while reading a line.


Solution

  • Akash, you are running into problems because you are failing to quote your variables which invites word-splitting of output from echo (and any of the other commands) giving the impression that whitespace was not preserved. To correct the problem, always Quote your variables, e.g.

    #!/bin/bash
    
    while IFS= read -r l 
    do
        echo "$l"
        echo "$l" > tempf
        wc -L tempf | cat > length
        len=$(cut -d " " -f 1 length)
        echo "$len"
    done < "$1"
    

    Example Input File

    $ cat fn
    who -all
               system boot  2019-02-13 10:27
               run-level 5  2019-02-13 10:27
    LOGIN      tty1         2019-02-13 10:27              1389 id=tty1
    david    ? :0           2019-02-13 10:27   ?          3118
    david    - console      2019-02-13 10:27  old         3118 (:0)
    

    Example Use/Output

    $ bash readwspaces.sh fn
    who -all
    8
               system boot  2019-02-13 10:27
    40
               run-level 5  2019-02-13 10:27
    40
    LOGIN      tty1         2019-02-13 10:27              1389 id=tty1
    66
    david    ? :0           2019-02-13 10:27   ?          3118
    58
    david    - console      2019-02-13 10:27  old         3118 (:0)
    63
    

    Also, for what it is worth, you can shorten your script to:

    #!/bin/bash
    
    while IFS= read -r l 
    do
        printf "%s\n%d\n" "$l" "${#l}"
    done < "$1"