在特定字符串之间替换字符 [英] Substitute characters between specific strings

查看:43
本文介绍了在特定字符串之间替换字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将两个特定字符串(DP 和 MQ)之间的每个逗号都替换为分号.

I would like to substitute every commas happen to be between two specific strings (DP & MQ) to semicolons.

输入

0,0,0,DP=1,1,1,1,MQ=2,2,2

预期输出

0,0,0,DP=1;1;1;1;MQ=2,2,2

我在 DP & 前后有可变数量的字段MQ 所以我认为 sed 是最好的.我不想在 DP 之前或 MQ 之后替换逗号.你们中的任何人都可以帮助我我知道它应该是这样的

I have variable number of fields before and after the DP & MQ so I thought sed would be the best. I don't want to substitute commas before DP or after MQ. Could any of you please help me I know that it should looks like this

sed 's/DP=.,.,.,.,MQ/DP=somethingMQ/g'

sed 's/DP=.,.,.,.,MQ/DP=somethingMQ/g'

提前致谢

推荐答案

这可能对你有用(GNU sed):

This might work for you (GNU sed):

sed -r 's/DP.*MQ/\n&\n/;h;y/,/;/;G;s/.*\n(.*)\n.*\n(.*)\n.*\n/\2\1/' file

这个 sed 习惯用法,标记有问题的字符串(使用换行符),复制标记的行,更改字符串,然后将原始行与更改后的字符串组合.

This sed idiom, marks the string in question (using newlines), copies the marked line, alters the string and then combines the original line with the altered string.

字符串的标记可能必须更具体,即:

The marking of the string may have to be more specific i.e.:

sed -r 's/DP=[^=]*MQ=/\n&\n/;h;y/,/;/;G;s/.*\n(.*)\n.*\n(.*)\n.*\n/\2\1/' file

如果只有部分文件可能包含有问题的字符串,请使用:

If only some of file may contain the string in question use:

sed -r '/DP=[^=]*MQ=/{s//\n&\n/;h;y/,/;/;G;s/.*\n(.*)\n.*\n(.*)\n.*\n/\2\1/}' file     

这篇关于在特定字符串之间替换字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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