即使存在,线也不会被掠过

时间:2017-01-12 17:43:03

标签: shell if-statement awk grep line

我正在使用以下代码来grep满足下面在代码中指定的条件的值。要grepped的行应满足文件中存在第2列-1值或第3列+ 1值的条件在场。

 while read intron ; do
 start=$(grep -w $intron ../file_to_be_grepped_from | awk '{print ($2-1)}')
 end=$(grep -w $intron ../file_to_be_grepped_from | awk '{print ($3+1)}')
  if (grep  $start ../file_to_be_grepped_from | grep -q :E) && (grep $end ../file_to_be_grepped_from | grep -q :E) ; then
    grep -w $intron ../file_to_be_grepped_from
  fi 
 done <  another_file

但是我收到以下错误:

 grep: 46844233: No such file or directory
 grep: 46844359: No such file or directory
 grep: 40174126: No such file or directory
 grep: 40174403: No such file or directory
 grep: 40176362: No such file or directory
 grep: 40174671: No such file or directory
 grep: 31542739: No such file or directory

除了40174403和40174671之外,文件中不存在大多数值。应该是grepped(并且存在)但不是这样的行:

  chr19 40174127    40174403    ENSG00000226025:E4  +
  chr19 40174671    40174788    ENSG00000226025:E5  +

欢迎任何纠正和改进代码的建议。 我的输入看起来像这样:

ENSG00000225518:I2
ENSG00000225535:I1
ENSG00000225535:I2
ENSG00000225535:I3
ENSG00000226025:I4

,预期输出为

chr1    226274755   226277190   ENSG00000225518:I2  + 
chr7    114719164   114758265   ENSG00000225535:I1  +
chr7    114758880   114758988   ENSG00000225535:I2  +
chr7    114759111   114762231   ENSG00000225535:I3  +
chr19   40174404    40174670    ENSG00000226025:I4  +

1 个答案:

答案 0 :(得分:2)

首先,为了防止出现grep错误消息,您可以通过用双引号括起多个$var扩展来更正代码:

while read intron ; do
  start=$(grep -w "$intron" ../file_to_be_grepped_from | awk '{print ($2-1)}')
  end=$(grep -w "$intron" ../file_to_be_grepped_from | awk '{print ($3+1)}')
  if   (grep "$start" ../file_to_be_grepped_from | grep -q :E) &&
       (grep "$end" ../file_to_be_grepped_from | grep -q :E)
  then
       grep -w "$intron" ../file_to_be_grepped_from
  fi 
done <  another_file

grep命令的第一个非选项参数是要查找的模式。接下来的参数是要查看的文件。如果变量intron包含由空格分隔的多个值,例如blablabla 46844233 46844359,则grep -w $intron会扩展为grep -w blablabla 46844233 46844359,其中blablabla是要查找的模式,{ {1}}和4684423346844359将尝试打开的文件的名称。