使用Bash脚本读取文件

32

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

这是我的代码:

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

错误:

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

2
这段代码没有任何问题。脚本中是否还有其他内容?也许是另一个whileif,或者引号、大括号、方括号或圆括号不平衡了? - Dennis Williamson
# or - it might be copy-pasted (with some rich text, Which is messing up the file itself) how-why-what-is this I am typing? uhm; it have (put simply) happened to me a bunch--of-times when I copy-pasting code into libreoffice, then copy-pasting it back(having colored the text) so some in-visible characters also get's copied - really weird - but it still is the same problem; to solve it you just by-hand type it(cat directory...`) (for long files this is a problem) (for short snippets like this one, it's easily and quickly typed)Just needed to throw that in for any future explorer - William Martens
4个回答

120

在这里使用 cat 没有任何必要 -- 它不会增加任何功能,而且还会产生一个不必要的进程。

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

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

foo=$(<file)
(请注意,这会剪切掉末尾的换行符。)

7
我希望我能多次点赞这个内容并确保它是每个Google搜索的顶部结果。在过去的一个小时里,我用很多方式表达了这个问题,但直到现在每次都会找到类似于“使用cat”的答案。最后,理智的一行回答出现了(与cat不同,它简单有效)。 - ArtOfWarfare
1
感谢您的编辑,@gniourf_gniourf - 每天都能学到新东西! - Adam Liss
@AdamLiss @ArtOfWarfare 有没有一种方法可以通过该方法定义一个变量,以保留“things”或“lines”的数量?比如,“对于每一行执行ECHO LINE,但同时也执行ECHO NUMBER”?我的意思不是另一个for,但我想知道read是否有这样的功能?例如,将read->file line by line's CONTENTS读入variable_A,同时将read->file line by line'S NUMBER读入variable_B?有的话就好了,否则还是谢谢 - 祝你有愉快的一天! - William Martens
2
@WilliamMartens - 是的,但是很快你就会问自己为什么要在bash中做这么多事情,而不是使用Python或其他脚本语言。 (不,我不知道你的答案,但我相信有一个答案。在SO上搜索-我相信它以前已经被问过并得到了回答。如果没有,请发布一个新问题。) - ArtOfWarfare
2
@WilliamMartens:i=0; while read line; do ((i=i+1)); echo "第 $i 行: $line"; done < file   你还可以通过使用 grep -n 来搜索每行匹配的内容,并对结果进行编号:   grep -n '' file | while read...   @ArtOfWarfare 我也无法控制,我的母语是 Bash。 ️   多么美好啊,看到一个问题和答案在10年后仍然与时俱进! - Adam Liss
显示剩余3条评论

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

编辑:

要将文件内容存储到变量中,请使用以下代码:

foo="`cat file`"

1
test.sh: 第5行:`done'附近有语法错误 - Leonardo
请检查一下这个链接:https://stackoverflow.com/questions/56459572/replace-a-string-in-a-file-with-contents-copied-from-another-file?noredirect=1#comment99510991_56459572 - nr5

4

这应该可以正常工作:

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

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

0

试一下

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接