2013-08-23 53 views
-1

我正在使用shell我有一个3列的文件,我想要的是在2和3列中搜索两个不同的字符串。我认为awk将是有用的,但我找不到一个方法来做到这一点。在两列中搜索两个不同的字符串

输入文件:

0000: 3.302295 22.508675 
0001: 2.913368 14.100854 
0002: 3.530211 19.428879 
0003: 3.239985 16.981230 
0004: 3.088717 25.245083 
0005: 3.156010 3.785273 

我想给像3.30和22.5两个搜索字符串,并给作为输出的第一行

0000:3.302295 22.508675

感谢

+0

请提供一些示例输入和所需的输出。否则,我想,答案太抽象了。 – fedorqui

+0

向我们展示1)示例输入(3列文件)2)两个搜索字符串,3)预期输出,4)更好的代码。 – Kent

回答

0

这个怎么样?

#!/bin/bash 

if [ ! $# -eq 2 ]; then 
    echo "Wrong number of parameters" 
    exit 
fi 

awk -v str1=$1 -v str2=$2 ' 
{ 
    if (match($2, "^" str1) && match($3, "^" str2)) { 
      print $0; 
    } 
}' 

例子:

./search.sh 3.175399 21.913555 < input.txt 

我假设上面的脚本名为search.sh和你输入input.txt中被stoted。

更新时间:添加正则表达式锚由格伦·杰克曼

+0

这是我真正想要的东西! 谢谢:-) – user2710445

+0

必须小心:如果你想匹配word的*开头*,你需要一个正则表达式锚点:'awk -v str1 =“$ 1”-v str2 =“$ 2”'match ($ 2,“^”str1)&& match($ 3,“^”str2)“' –

+0

谢谢!如果想要一个范围的值? 第一个字符串从4到6和第二个字符串从2到4类似? – user2710445

0

的建议这应该为你工作:

awk -F, '{ if ($2 == "\"3.30\"" && $3 == "\"22.5\"") print $0 }' <filename> 

我希望它能帮助! :)

0

一个简单的grep看起来像它可能做的伎俩:

#!/bin/bash 

echo -n "First number : " 
read n1 
echo -n "Second number : " 
read n2 

# Match lines containing first number, any number of characters, and second number. 
grep "$n1.*$n2" your_file 

这个代码是有点过于简单化。也许你想输入整数如3和1 ...在这种情况下,每行包含一个3,然后在某处匹配。考虑到这一点,下面是一个解决方案:

#!/bin/bash 

echo -n "First number : " 
read n1 
echo -n "Second number : " 
read n2 

# Adding decimal separators in case of whole numbers 
if [[ $n1 != *.* ]] 
then 
    n1=${n1}\\. 
fi 

if [[ $n2 != *.* ]] 
then 
    n2=${n2}\\. 
fi 

# Match lines containing first number, any number of characters, and second number. 
grep "$n1.*$n2" your_file 
相关问题