在bash中读取文件时保留前导空格

时间:2014-03-20 16:11:44

标签: bash parsing

也许有人能给我一个解决我问题的线索 让我们假设我有这两行:

blablablabla
 blablablabla

(第二行以空格开头)

我试着在我的线上测试第一个角色:

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

在这两种情况下,check = 'b'!这很烦人,因为我需要这些信息用于治疗的其余部分。

2 个答案:

答案 0 :(得分:3)

您需要为IFS指定空字符串,以便read不会丢弃前导或尾随空格:

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

答案 1 :(得分:0)

@Chepner的回答是正确的,我只是添加手册的相关部分:

   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.