0

我正在尝试创建一个验证文件的 bash 脚本。其中一项要求是文件中必须有一个“2”。

这是我目前的代码:

regex1="[0-9b]*2[0-9b]*2[0-9b]*"

# This regex will match if there are at least two 2's in the file
if [[ ( $(cat "$file") =~ $regex1 ) ]]; then
    # stuff to do when there's more than 1 "2"
fi

#...


regex2="^[013456789b]*$"
# This regex will match if there are at least no 2's in the file
if [[ ( $(cat "$file") =~ $regex2 ) ]]; then
    # stuff to do when there are no 2's
fi

我想要做的是匹配以下部分:

654654654654
254654845845
845462888888

(因为里面有2个2,应该是匹配的)

987886546548
546546546848
654684546548

(因为里面没有2,所以应该匹配)

知道如何让它使用=~运算符搜索所有行吗?

4

4 回答 4

3

我正在尝试创建一个验证文件的 bash 脚本。其中一项要求是文件中必须有一个“2”。

尝试使用grep

#!/bin/bash

file='input.txt'

n=$(grep -o '2' "$file" | wc -l)
# echo $n

if [[ $n -eq 1 ]]; then
  echo 'Valid'
else
  echo 'Invalid'
fi
于 2013-11-11T14:58:03.870 回答
1

这个怎么样:

twocount=$(tr -dc '2' input.txt | wc -c)
if (( twocount != 1 ))
then
  # there was either no 2, or more than one 2
else
  # exactly one 2
fi
于 2013-11-11T15:24:36.033 回答
0

像以前一样使用锚点,匹配一串非2s、a2和另一串非2s。

^[^2]*2[^2]*$
于 2013-11-11T14:31:23.400 回答
0

awk使用with确实可以进行多行正则表达式匹配null record separator

考虑下面的代码:

awk '$0 ~ /^.*2.*2/ || $0 ~ /^[013456789]*$/' RS= file
654654654654
254654845845
845462888888

请注意RS=这使得 awk 将多行连接成单行$0,直到遇到双换行符。

于 2013-11-11T15:10:15.460 回答