2013-09-29 82 views
1

我有这种类型的数据(所有大字母串)替换文本由特定字符

>A|B|C|D|E|F 
test test test 
test test 
>A|B|C|D|E|F 
test test test 
test 

,并希望删除C,d,E包围文本,没有|发生。我已经用sed试过了,但是Im无法替换之后出现的文字|
提前致谢。

+0

所以你的真实数据,你必须多字的领域和你没有“| “分隔领域,对吗?也许对你发布样本输入和期望的输出反映那么是有用的,而不是用“|”分隔的单字符字段。只是把它扔在那里...... –

+0

是的,你是对的。通用样本输入可能会令人困惑。 – Atticus

回答

3

的Perl oneliner,

perl -F'\|' -lane 'print /\|/ ? join "|", @F[0,1,5] : $_' file 

它由分割每行char和store的值在@F数组中。如果行包含|,它将从@F获取元素0,1和5,否则保持原样。

Oneliner deparsed,

perl -MO=Deparse -F'\|' -lane 'print /\|/ ? join "|", @F[0,1,5] : $_' file 
BEGIN { $/ = "\n"; $\ = "\n"; }   # -l switch makes print to add newline 
LINE: while (defined($_ = <ARGV>)) { # -n switch 
    chomp $_;       # -l switch chomps newlines 
    our(@F) = split(/\|/, $_, 0);  # -a switch splits on value of -F switch 
    print /\|/ ? join('|', @F[0, 1, 5]) : $_; 
} 
+0

谢谢,它的作品!你能简单地解释一下代码吗? – Atticus

2

sed正常工作:

$ cat 1 
>A|B|C|D|E|F 
test test test 
test test 
>A|B|C|D|E|F 
test test test 
test 
$ sed 's/C|D|E|//' 1 
>A|B|F 
test test test 
test test 
>A|B|F 
test test test 
test 

UPDATE

$ sed 's/\([^|]|[^|]|\).*|/\1/' 1 
>A|B|F 
test test test 
test test 
>A|B|F 
test test test 
test 
+0

也许我的问题不清楚。 A,B,C,D,E,F是字符串。一个例子是:'> gene_8 | GeneMark.hmm | 322_aa | + | 3803 | 4771TS28_contig03869'。我想从字符串中独立删除内容。 – Atticus

+1

@Atticus,我添加了另一个代码。一探究竟。 – falsetru

2

也许适合此

awk --re-interval -F'|'\ 
     'NF > 4{$0=gensub(/^(([^|]*\|){2})([^|]*\|){3}(.*)$/, "\\1\\4", -1)}; 
     {print}' file 
+1

仅供参考,您只需要'--re-interval'在旧gawk版本中,这是最近gawks中的默认行为(不,我不知道什么时候改变了,但已经有一段时间了)。另外,你不需要设置OFS,因为你不会重新编译记录,而只需执行'$ 0 = gensub(...)'并丢失中间变量'z'。 –

+0

@EdMorton,好点,合并。我正在离开'--re-interval',因为我的版本的GNU'awk'(3.1.8)似乎需要它 – iruvar

1

这应该这样做。 -i选项指定要在原地编辑文件。

perl -i.bak -pe 's/\|[CDE]//g' file 

或使用sed的

sed -i.bak -re 's/\|[CDE]//g' file 
3
$ cat file 
>A|B|C|D|E|F 
test test test 
test test 
>A|B|C|D|E|F 
test test test 
test 
>gene_8|GeneMark.hmm|322_aa|+|3803|4771TS28_contig03869 
test test test 
test test 
$ 
$ sed -r 's/(([^|]+\|){2})(([^|]+\|){3})/\1/' file 
>A|B|F 
test test test 
test test 
>A|B|F 
test test test 
test 
>gene_8|GeneMark.hmm|4771TS28_contig03869 
test test test 
test test 
0

awk的正常工作,以及:

awk '{sub(/C\|D\|E\|/,"")}1' file 
>A|B|F 
test test test 
test test 
>A|B|F 
test test test 
test