musecz
musecz

Reputation: 805

Preserving leading whitespace when reading a file in bash

Maybe someone could give me a clue for my problem.
Let's suppose I have this two lines:

blablablabla
 blablablabla

(the second line begins with a space)

I tried to test the first character on my line:

while read line
do
    check=${line:0:1}
done < file.txt

In both cases, check = 'b' ! That's annoying, because I need this information for the rest of the treatment.

Upvotes: 2

Views: 616

Answers (2)

just somebody
just somebody

Reputation: 19247

@chepner's answer is correct, i'll just add relevant part of the manual:

   read [-ers] [-a aname] [-d delim] [-i text] [-n nchars] [-N nchars] [-p
   prompt] [-t timeout] [-u fd] [name ...]
          One  line  is  read  from  the  standard input, or from the file
          descriptor fd supplied as an argument to the -u option, and  the
          first word is assigned to the first name, the second word to the
          second name, and so on, with leftover words and their  interven-
          ing  separators  assigned  to the last name.  If there are fewer
          words read from the input stream than names, the remaining names
          are  assigned  empty  values.  The characters in IFS are used to
          split the line into words.

Upvotes: 0

chepner
chepner

Reputation: 531165

You need to specify the empty string for IFS so that read doesn't discard leading or trailing whitespace:

while IFS= read line; do
    check=${line:0:1}
done < file.txt

Upvotes: 4

Related Questions