我需要使用“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'
我需要使用“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'
在这里使用 cat
没有任何必要 -- 它不会增加任何功能,而且还会产生一个不必要的进程。
while IFS= read -r line; do
echo "a line: $line"
done < file
要将文件的内容读入变量中,使用
foo=$(<file)
(请注意,这会剪切掉末尾的换行符。)read
是否有这样的功能?例如,将read->file line by line's CONTENTS
读入variable_A
,同时将read->file line by line'S NUMBER
读入variable_B
?有的话就好了,否则还是谢谢 - 祝你有愉快的一天! - William Martensi=0; while read line; do ((i=i+1)); echo "第 $i 行: $line"; done < file
你还可以通过使用 grep -n
来搜索每行匹配的内容,并对结果进行编号: grep -n '' file | while read...
@ArtOfWarfare 我也无法控制,我的母语是 Bash。 ️ 多么美好啊,看到一个问题和答案在10年后仍然与时俱进! - Adam Lisscat file | while read line
do
echo "a line: $line"
done
编辑:
要将文件内容存储到变量中,请使用以下代码:
foo="`cat file`"
这应该可以正常工作:
file=path/of/file/location/filename.txt
while IFS= read -r varname; do
printf '%s\n' "$varname"
done < "$file"
试一下
while read p
do
echo $p
done < directory/scripts/tv2dbarray.txt
while
或if
,或者引号、大括号、方括号或圆括号不平衡了? - 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