使用 bash 脚本读取文件

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

Read a file using a bash script

bash

提问by Leonardo

I need to read a file using a "Do/While" loop.
How can I read the contents as a string?

我需要使用“Do/While”循环读取文件。
如何将内容作为字符串读取?

Here's my code:

这是我的代码:

cat directory/scripts/tv2dbarray.txt | while read line
do
  echo "a line: $line"
done

Error:

错误:

test.sh: line 4: syntax error near unexpected token `done'
test.sh: line 4: `done'

回答by Adam Liss

There's no reason to use cathere -- it adds no functionality and spawns an unnecessary process.

没有理由在cat这里使用——它不添加任何功能并产生一个不必要的过程。

while IFS= read -r line; do
  echo "a line: $line"
done < file

To read the contents of a file into a variable, use

要将文件的内容读入变量,请使用

foo=$(<file)

(note that this trims trailing newlines).

(请注意,这会修剪尾随的换行符)。

回答by Erik

cat file | while read line
do
  echo "a line: $line"
done

EDIT:

编辑:

To get file contents into a var use:

要将文件内容放入 var 使用:

foo="`cat file`"

回答by prudviraj

This should work:

这应该有效:

file=path/of/file/location/filename.txt

while IFS= read -r varname; do
    printf '%s\n' "$varname"
done < "$file"

回答by pedram shabani

try it

尝试一下

while read p
do 
echo $p
done <  directory/scripts/tv2dbarray.txt