regex - 通过在特定位置添加前缀来编辑文件

标签 regex bash unix sed

我有一个如下所示的文件:

fixedStep chrom=20 start=1 step=1000   
0   
10   
20   
100   
0  
fixedStep chrom=19 start=1 step=1000   
0   
0   
50   
330   
450   
0

我想为 chrom= 之后的数字添加前缀 chr。因此,我不想使用 chrom=20chrom=19,而是想要 chrom=chr20chrom=chr20.所以该文件应如下所示:

fixedStep chrom=chr20 start=1 step=1000   
0   
10   
20   
100   
0  
fixedStep chrom=chr19 start=1 step=1000   
0   
0   
50   
330   
450   
0

我知道使用 sed 命令我能够做到这一点,但我不知道如何构造一个找到 正则表达式 chrom = 部分。我已经使用 sed 来修改简单的事情,例如在文件中每行的开头添加前缀;但我无法全神贯注于这个问题!

最佳答案

您可以使用此sed命令:

sed 's/\(chrom=\)/\1chr/g' file
fixedStep chrom=chr20 start=1 step=1000
0
10
20
100
0
fixedStep chrom=chr19 start=1 step=1000
0
0
50
330
450
0

\(chrom=\) 搜索 chrom= 并将其捕获到组 #1 中,以用于替换模式 \1chr

或者更简单:

sed 's/chrom=/&chr/g' file

关于regex - 通过在特定位置添加前缀来编辑文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26510015/

相关文章:

unix - 为什么 TOMCAT 服务器在 unix 中自动重启?

javascript - 测试第三级斜杠的正则表达式?

javascript - 用于强制特殊标题格式的正则表达式

bash - 如何将 yaml 文件读入 bash 关联数组?

linux - 为什么sudo下运行的tcpdump超时不能生效?

bash - 在 unix shell 中更改目录(特殊字符)

regex - Sublime Text :正则表达式删除不以开头的行

java - 将正则表达式中的字符串拆分为 - 作为一个单词

linux - BASH:如何使用脚本复制文件名并将其插入到文本中?

linux - 如何以编程方式在 Linux 中截取应用程序的屏幕截图?