2

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.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
musecz
  • 797
  • 7
  • 17
  • 1
    FYI, if you didn't pass `line` to `read`, and used the default `REPLY` variable, that too would solve your problem here. It's only the form where you pass in a list of destinations where `IFS` is used to trim and split by whitespace. – Charles Duffy Mar 20 '14 at 16:21
  • Updated title -- there's no actual parsing going on here. – Charles Duffy Mar 20 '14 at 16:23

2 Answers2

4

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
chepner
  • 497,756
  • 71
  • 530
  • 681
0

@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.
just somebody
  • 18,602
  • 6
  • 51
  • 60