使用 Bash 逐行读取并保留空间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7314044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 21:00:25  来源:igfitidea点击:

Use Bash to read line by line and keep space

bash

提问by paler

When I use "cat test.file", it will show

当我使用“cat test.file”时,它会显示

1
 2
  3
   4

When I use the Bash file,

当我使用 Bash 文件时,

cat test.file |
while read data
do
    echo "$data"
done

It will show

它会显示

1
2
3
4

How could I make the result just like the original test file?

我怎样才能使结果与原始测试文件一样?

回答by DigitalRoss

IFS=''
cat test.file |
while read data
do
    echo "$data"
done

I realize you might have simplified the example from something that really needed a pipeline, but before someone else says it:

我意识到您可能已经从真正需要管道的东西中简化了示例,但在其他人说之前:

IFS=''
while read data; do
    echo "$data"
done < test.file

回答by Joshua Davies

Actually, if you don't supply an argument to the "read" call, read will set a default variable called $REPLY which will preserve whitespace. So you can just do this:

实际上,如果您不为“read”调用提供参数,则 read 将设置一个名为 $REPLY 的默认变量,该变量将保留空格。所以你可以这样做:

$ cat test.file | while read; do echo "$REPLY"; done

回答by diogovk

Just to complement DigitalRoss's response.

只是为了补充 DigitalRoss 的回应。

For that case that you want to alter the IFSjust for this command, you can use curly braces. If you do, the value of IFS will be changed only inside the block. Like this:

对于您只想为此命令更改IFS的情况,您可以使用花括号。如果这样做,IFS 的值将仅在块内更改。像这样:

echo '
  word1
  word2' |  { IFS='' ; while read line ; do echo "$line" check ; done ; }

The output will be (keeping spaces):

输出将是(保留空格):

  word1 check
  word2 check

回答by plhn

Maybe IFSis the key point as others said. You need to add only IFS=between whileand read.

也许IFS是其他人所说的关键点。您只需要IFS=while和之间添加read

cat test.file | 
while IFS= read data 
 do echo "$data"
 done

and do not forget quotations of $data, else echowill trim the spaces.

并且不要忘记 的引号$data,否则echo会修剪空格。

But as Joshua Davies mentioned, you would prefer to use the predefined variable $REPLY.

但正如Joshua Davies 提到的,您更愿意使用预定义的变量$REPLY

回答by Mu Qiao

read datawill split the data by IFS, which is typically " \t\n". This will preserve the blanks for you:

read data将按IFS拆分数据,通常是“\t\n”。这将为您保留空白:

var=$(cat test.file)
echo "$var"

回答by ghostdog74

Alternatively, use a good file parsing tool, like AWK:

或者,使用一个好的文件解析工具,如AWK

awk '{
  # Do your stuff
  print 
}' file