使用bash脚本逐行读取文件

nan*_*ips 3 regex bash command if-statement

我需要一个bash脚本来逐行读取文件.如果正则表达式匹配,则回显此行.

该脚本如下:

#!/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
Run Code Online (Sandbox Code Playgroud)

它正在打印文件内容,但显示此警告:

./script: line 7: regex: command not found
Run Code Online (Sandbox Code Playgroud)

错误在哪里?

Fre*_*ihl 6

其他人已经提供了关于使用的实际正则表达式的提示.循环遍历文件中所有行的正确方法是:

#!/bin/bash

regex='[0-9]'

while read line
do
    if [[ $line =~ $regex ]]
    then
        echo $line
    fi
done < input
Run Code Online (Sandbox Code Playgroud)


tha*_*guy 4

=本例中的问题是登录周围的空格regex = '^[0-9]+/[0-9]+/[0-9]+$'

它应该是

regex='^[0-9]+/[0-9]+/[0-9]+$'
Run Code Online (Sandbox Code Playgroud)

ShellCheck会自动警告您这一点,并且还建议在哪里引用变量以及如何逐行读取(您当前正在逐字执行)。