在shell脚本中grepping包含特殊字符的变量 [英] grepping variables containing special characters in a shell script

查看:353
本文介绍了在shell脚本中grepping包含特殊字符的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图根据存储在bash脚本中变量中的模式(可能包含()[])从文件中删除某些行.使用不包含特殊字符但使用()的模式得到所需的输出,我得到空白输出,使用[]的情况得到以下错误: grep:字符类中的顺序混乱

I am trying to grep out some lines from a file based on patterns stored in a variable in bash script that may contain (, ), [ or ]. I get the desired output with patterns that do not contain the special characters but with ( or ), I get a blank output and with [ or ], I get the following error: grep: range out of order in character class

特征码文件示例:

14-3-3-like protein B
14-3-3-like protein B (Fragment)
3-oxoacyl-[acyl-carrier-protein] synthase 2

输入文件示例:

seq1    gi|703124372    380    285    +    2e-154    14-3-3-like protein B    sp
seq2    Q96451    69    51    +    3e-16    14-3-3-like protein B (Fragment)    sp
seq3    P0AAI5    104    84    -    4e-20    3-oxoacyl-[acyl-carrier-protein] synthase 2    sp

我的代码如下:

if [ $@==0 ]
    then echo -e "\nUSAGE: $0 [pattern file] [in file] > [out file]\n"
    exit;
else
    while read line; do
            echo -e "Pattern: $line"
            grep -P "\t$line\t" $2
            echo -e "\n"
    done < $1

输出样本:

Pattern: 14-3-3-like protein B 
seq1    gi|703124372    380    285    +    2e-154    14-3-3-like protein B    sp
Pattern: 14-3-3-like protein B (Fragment)    sp
Pattern: 3-oxoacyl-[acyl-carrier-protein] synthase 2
grep: range out of order in character class

我尝试使用grep -Fw,但这也无法提供所需的输出. 我也尝试用\(\[代替([替换两个输入文件中的模式,但这也不起作用.

I've tried using grep -Fw but that also doesn't give the desired output.. I've also tried substituting the patterns in the two input files with \( and \[ instead of ( and [ but that also doesn't work..

任何想法我该如何实现?还有什么可以代替grep的?

Any idea how can I achieve this? Is there anything else I could use instead of grep?

推荐答案

tab=$(echo -e \\t)
grep -F "$tab$line$tab" $2

另请参阅@anubhava的建议:grep -F $'\t'"$line"$'\t' "$2"

See also the suggestion from @anubhava: grep -F $'\t'"$line"$'\t' "$2"

这篇关于在shell脚本中grepping包含特殊字符的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆