Search code examples
bashwhile-loopcut

bash: preserve white character when cutting in a while loop


it looks like while read line discards the blank first characters

while read line; 
 do DB=$(  echo "$line" | cut -c1-8);           
 echo DB=$DB; 
 echo $line; 
done < histogram.txt

text

      7107: ( 12,255,  0) #0CFF00 srgb(12,255,0)
      4514: ( 12,255,255) #0CFFFF srgb(12,255,255)
     11580: ( 30,  0,253) #1E00FD srgb(30,0,253)
     14365: (246,255,  0) #F6FF00 srgb(246,255,0)
     29576: (255,  0,  0) #FF0000 red
____188858: (255,255,255) #FFFFFF white

expected result for line 1 "....7107" (. = space) what I really get "7107: ( "

the last line works ("____1888") because I replaced space by underscore result

SO how do I get the blank characters ?


Solution

  • You need 2 things:

    1. set IFS to a null string for the read command: while IFS= read -r line -- that will preserve all whitespace into the variable

    2. quote the variable everywhere you use it: echo "$line"

    while IFS= read -r line; do
      DB="${line:1:8}"
      echo "DB=$DB"
      echo "$line"
    done < histogram.txt
    

    bash parameter substution can take a substring, so you don't need cut