2012-04-27 62 views
0

我有一个文件有不同的文本行,我想检查是否是相同模式的重复。查找字符串中的模式linux

在文件:

Blah 
Blah 
Depends: ssloader, firmware (>= 3.0), firmware (<= 6.0), apta 
blah 

我的目标是让 “> = 3.0” & “< = 6.0” 到文件中。但请记住,有时只有1个“固件”依赖性。

我有什么到目前为止,只有抓住了第一次固件信息:

if grep -Fq "firmware (" inputfile #checks if pattern exists 
then 
compat=$(look 'Depends:' inputfile) #grab line where pattern is 
compat=${##*firmware (} #remove pattern and other stuff infront 
compat=${compat%%)*} #remove other stuff behind ")" 
echo $compat >> outputfile 
fi 

我想知道如何检查,如果有在同一行超过1种模式。或者如果有超过1行的模式相同,如何识别该行可以获得固件值。由于

编辑:

我最初的目的是检测是否有相同图案的不止一个。我对想法持开放态度。 :)

是这样的:

if (more than one of same pattern) 
get both values #I am open to ideas to get this done <--- 
else 
get value of this pattern 
fi 

EDIT2:

我做它像这样得到这个工作;

if grep -Fq "firmware (" ./control 
then 
    compat=$(look 'Depends:' control) 
    compat=${compat#*firmware (} 
    compat=${compat%%)*} 
    echo -n $compat > ./compatibility.txt 
    if [ $(grep -o "firmware (" ./control | wc -l) -eq 2 ]; then 

    compat=$(look 'Depends:' control) 
    compat=${compat##*firmware (} 
    compat=${compat%%)*} 
    echo " $compat" >> ./compatibility.txt 
    fi 
fi 

我知道这绝对是非常外行,而且它只能如果模式是在“依赖”的标签。

任何想法/输入?

+0

是它始终将是'firmware',或者是你在寻找任何重复'取决于:',或任何标记行中的任何重复? – geekosaur 2012-04-27 03:43:58

+0

另外,可能会有多少重复? – geekosaur 2012-04-27 03:51:30

+0

它有时会成为'firmware',其他标签如'Pre-depends:'可能有'firmware'信息。 – AlwynIsPat 2012-04-27 03:52:27

回答

1

如果是正常使用sed

sed -n '/firmware (/ { s/[^(]*(\(\([<>]=\|=\|[<>]\)\s\+[0-9]\+\(\.[0-9]\+\)*\))[^(]*/\1 /g; p }' file 

样品输入:

Blah 
Blah 
Depends: ssloader, firmware (>= 3.0), firmware (<= 6.0), firmware (= 5.0), apta 
Depends: ssloader, firmware (>= 3.0), firmware (<= 6.0), apta 
Depends: ssloader, firmware (<= 6.0), apta 
blah 

样本输出:

>= 3.0 <= 6.0 = 5.0 
>= 3.0 <= 6.0 
<= 6.0 
+0

我真的很喜欢这个,但它可以被增强,所以如果只取得'固件'的价值? '取决于:ssloader,固件(> = 3.0),subr(0.222-1),固件(<6.0),apta'。 它是否工作,如果'固件(> 6.0)'?(请注意,没有'=') – AlwynIsPat 2012-05-29 05:18:09

+0

@AlwynIsPat查看我的编辑。我使用了几个gsed扩展使它更短,所以让我知道如果你没有gsed,我会使用更长的版本。 – 2012-05-29 16:58:52

1

另一个sed版本,这可能会更好地工作,这取决于你're doing:

sed -n 's/.* firmware (\([^)]*\)),.* firmware (\([^)]*\)),.*$/\1 \2/p' 

(这是比较容易推广为多个包,顺便)

+0

如果只有一个“固件实例”,那么这将会失败,如果你拿出''*'',也许你可以使第二个选项成为可选项。 – 2012-04-27 04:16:13

+0

我对“多于一个模式”的阅读没有包括1.是否应该?(这个问题似乎是专门寻找重复的信息。) – geekosaur 2012-04-27 04:17:39

+0

嗯,也许是这样。我读了“最重复的,2.”,意思是在sed说'\ {1,2 \}'也似乎他们的程序已经适应了有一个的情况,但他们希望它可以容纳多达两个。也许OP应该澄清一下。 – 2012-04-27 04:21:50