19

I want to read a file line by line in Unix shell scripting. Line can contain leading and trailing spaces and i want to read those spaces also in the line. I tried with "while read line" but read command is removing space characters from line :( Example if line in file are:-

abcd efghijk
 abcdefg hijk

line should be read as:- 1) "abcd efghijk" 2) " abcdefg hijk"

What I tried is this (which not worked):-

while read line
do
   echo $line
done < file.txt

I want line including space and tab characters in it. Please suggest a way.

4

2 回答 2

26

尝试这个,

IFS=''
while read line
do
    echo $line
done < file.txt

编辑:

man bash

IFS - The Internal Field Separator that is used for word
splitting after expansion and to split lines into words
with  the  read  builtin  command. The default value is
``<space><tab><newline>''
于 2013-05-28T11:04:01.150 回答
18

您想阅读原始行以避免输入中的反斜杠问题(使用-r):

while read -r line; do
   printf "<%s>\n" "$line"
done < file.txt

这将保留行内的空格,但删除前导和尾随空格。要保留这些,请将 IFS 设置为空,如

while IFS= read -r line; do
   printf "%s\n" "$line"
done < file.txt

现在这相当于cat < file.txtas long 以file.txt换行符结尾。

请注意,您必须双引号"$line"以防止单词拆分将行拆分为单独的单词 - 从而丢失多个空格序列。

于 2013-05-28T11:04:32.260 回答