我有这种类型的数据(所有大字母串)替换文本由特定字符
>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无法替换之后出现的文字|
提前致谢。
我有这种类型的数据(所有大字母串)替换文本由特定字符
>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无法替换之后出现的文字|
提前致谢。
的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]) : $_;
}
谢谢,它的作品!你能简单地解释一下代码吗? – Atticus
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
也许gawk适合此
awk --re-interval -F'|'\
'NF > 4{$0=gensub(/^(([^|]*\|){2})([^|]*\|){3}(.*)$/, "\\1\\4", -1)};
{print}' file
仅供参考,您只需要'--re-interval'在旧gawk版本中,这是最近gawks中的默认行为(不,我不知道什么时候改变了,但已经有一段时间了)。另外,你不需要设置OFS,因为你不会重新编译记录,而只需执行'$ 0 = gensub(...)'并丢失中间变量'z'。 –
@EdMorton,好点,合并。我正在离开'--re-interval',因为我的版本的GNU'awk'(3.1.8)似乎需要它 – iruvar
这应该这样做。 -i
选项指定要在原地编辑文件。
perl -i.bak -pe 's/\|[CDE]//g' file
或使用sed的
sed -i.bak -re 's/\|[CDE]//g' file
$ 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
awk的正常工作,以及:
awk '{sub(/C\|D\|E\|/,"")}1' file
>A|B|F
test test test
test test
>A|B|F
test test test
test
所以你的真实数据,你必须多字的领域和你没有“| “分隔领域,对吗?也许对你发布样本输入和期望的输出反映那么是有用的,而不是用“|”分隔的单字符字段。只是把它扔在那里...... –
是的,你是对的。通用样本输入可能会令人困惑。 – Atticus