在bash中读取文件时保留前导空格
也许有人能为我的问题提供线索。在bash中读取文件时保留前导空格,bash,parsing,Bash,Parsing,也许有人能为我的问题提供线索。 假设我有两行: blablablabla blablablabla (第二行以空格开头) 我试图测试行中的第一个字符: while read line do check=${line:0:1} done < file.txt 读取行时 做 check=${line:0:1} 完成
假设我有两行:
blablablabla
blablablabla
(第二行以空格开头)
我试图测试行中的第一个字符:
while read line
do
check=${line:0:1}
done < file.txt
读取行时
做
check=${line:0:1}
完成
在这两种情况下,
check='b'
!这很烦人,因为我在治疗的其余部分需要这些信息。您需要为IFS
指定空字符串,以便read
不会丢弃前导或尾随空格:
while IFS= read line; do
check=${line:0:1}
done < file.txt
而IFS=读取行;做
check=${line:0:1}
完成
您需要为IFS
指定空字符串,以便读取
不会丢弃前导或尾随空格:
while IFS= read line; do
check=${line:0:1}
done < file.txt
而IFS=读取行;做
check=${line:0:1}
完成
@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.
@切普纳的回答是正确的,我只想在手册中添加相关部分:
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.
仅供参考,如果您没有将
行
传递到读取
,并使用默认的回复
变量,这也将解决您的问题。这只是一个表单,您可以在其中传递一个目的地列表,其中IFS
用于按空格进行修剪和分割。更新的标题--这里没有实际的解析。仅供参考,如果您没有将行
传递到读取
,并使用默认的回复
变量,那么这里的问题也会得到解决。它只是一种形式,您可以在其中传递一个目的地列表,IFS
用于按空格进行修剪和拆分。更新的标题--这里没有实际的解析。赋值的RHS在参数扩展后不进行分词。我不知道其他原因。赋值的RHS不进行分词参数扩展后。我不知道还有其他原因。