Saving spaces while reading a file in bash

Maybe someone can give me the key to my problem.
Suppose I have two lines:

blablablabla blablablabla 

(second line starts with a space)

I tried to check the first character on my line:

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

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

+1
bash parsing
source share
2 answers

You need to specify an empty string for IFS so that read does not remove spaces at the beginning or end:

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

@chepner's answer is correct, I will just add the corresponding 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. 
0
source share

All Articles