bash 使用bash脚本逐行读取文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21891730/
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
Read file line by line with bash script
提问by araujophillips
I need a bash script to read a file line by line. If a regex match, echo this line.
我需要一个 bash 脚本来逐行读取文件。如果正则表达式匹配,则回显这一行。
The script is the following:
脚本如下:
#!/bin/bash
echo "Start!"
for line in $(cat results)
do
regex = '^[0-9]+/[0-9]+/[0-9]+$'
if [[ $line =~ $regex ]]
then
echo $line
fi
done
It is printing the file content, but show this warning:
它正在打印文件内容,但显示此警告:
./script: line 7: regex: command not found
Where is the error?
错误在哪里?
回答by Fredrik Pihl
Others have given you hints about the actual regexp to use. The properway to loop over all the lines in a file is this:
其他人已经为您提供了有关要使用的实际正则表达式的提示。循环遍历文件中所有行的正确方法是:
#!/bin/bash
regex='[0-9]'
while read line
do
if [[ $line =~ $regex ]]
then
echo $line
fi
done < input
回答by that other guy
The problem in this case is the spaces around the =
sign in regex = '^[0-9]+/[0-9]+/[0-9]+$'
这种情况下的问题是=
登录周围的空格regex = '^[0-9]+/[0-9]+/[0-9]+$'
It should be
它应该是
regex='^[0-9]+/[0-9]+/[0-9]+$'
ShellCheckautomatically warns you about this, and also suggests where to quote your variables and how to read line by line (you're currently doing it word by word).
ShellCheck 会自动警告您这一点,并建议在何处引用您的变量以及如何逐行读取(您目前正在逐行阅读)。
回答by Stepan Grigoryan
Elimnate the spaces around regex:
消除正则表达式周围的空格:
regex='^[0-9]+/[0-9]+/[0-9]+$'