bash 使用for循环bash脚本逐行读取文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19058404/
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-10 00:15:11  来源:igfitidea点击:

Reading files line by line in by using for loop bash script

bashfor-loop

提问by OKC

Say for example I have a file called "tests",it contains

比如说我有一个名为“tests”的文件,它包含

a
b
c
d

I'm trying to read this file line by line and it should output

我正在尝试逐行读取此文件,它应该输出

a
b
c
d

I create a bash script called "read" and try to read this file by using for loop

我创建了一个名为“read”的 bash 脚本,并尝试使用 for 循环读取此文件

#!/bin/bash
for i in ; do //for the ith line of the first argument, do...
   echo $i  // prints ith line
done

I execute it

我执行它

./read tests

but it gives me

但它给了我

tests

Does anyone know what happened? Why does it print "tests" instead of the content of the "tests"? Thanks in advance.

有谁知道发生了什么?为什么它打印“测试”而不是“测试”的内容?提前致谢。

回答by Gilles Quenot

#!/bin/bash
while IFS= read -r line; do
  echo "$line"
done < ""

This solution can handle files with special characters in the file name (like spaces or carriage returns) unlike other responses.

与其他响应不同,此解决方案可以处理文件名中包含特殊字符(如空格或回车)的文件。

回答by bobah

You need something like this rather:

你需要这样的东西:

#!/bin/bash
while read line || [[ $line ]]; do
  echo $line
done < 

what you've written after expansion will become:

扩展后你写的将变成:

#!/bin/bash
for i in tests; do
   echo $i
done

if you still want forloop, do something like:

如果您仍然想要for循环,请执行以下操作:

#!/bin/bash
for i in $(cat ); do
   echo $i
done

回答by Michael

This works for me:

这对我有用:

#!/bin/sh

for i in `cat `
do
    echo $i
done