简体   繁体   English

使用sed替换多个字符

[英]Replacing multiple chars using sed

I have a string: 我有一个字符串:

xy-uv>ab-cd-ed-ef-gh<

I need to be convert it to: 我需要将其转换为:

xy-uv>ab cd ef gh<

Basically, I need to replace the - with a space in all characters between the > and the < . 基本上,我需要用><之间的所有字符替换-

How can I do this using sed ? 如何使用sed执行此操作?

One way to do this is: 一种方法是:

sed 'h; s/.*>\(.*\)<.*/\1/; s/-/ /g; G; s/\(.*\)\n\(.*>\)\(.*\)\(<.*\)/\2\1\4/'

In a multiline script it would be: 在多行脚本中,它将是:

h 
s/.*>\(.*\)<.*/\1/
s/-/ /g 
G 
s/\(.*\)\n\(.*>\)\(.*\)\(<.*\)/\2\1\4/

It is a common pattern when you want to make a substitution only for a specific part of a line. 当您只想替换一行的特定部分时,这是一种常见的模式。 It takes advantage of the hold space ( h , G commands). 它利用了保留空间( hG命令)。 Basically you make a copy of the line (from the pattern space) to the hold space. 基本上,您是将行的副本(从模式空间)复制到保留空间。 Then isolate the part between '>' and '<', and substitute '-' with ' '. 然后隔离“>”和“ <”之间的部分,并用“”替换“-”。 Then use the multiline get G command to append the hold space to the pattern space. 然后,使用多行get G命令将保留空间附加到模式空间。 In between there will be a new line character (the G command is a multiline command). 在两者之间会有一个换行符( G命令是多行命令)。 In the last line we simply rearrange the two lines using groups and the replacement metacharacters \\N (where N is the group number). 在最后一行中,我们仅使用和替换元字符\\ N(其中N是组号)重新排列这两行。

You can try this sed script : 您可以尝试以下sed脚本:

s/>([^>]+)</\n>\1<\n/g
:loop
s/(\n[>][^ ]+)-([a-z ]*[<]\n?)/\1 \2/g
t loop
s/\n//g

Test: 测试:

sat:~# sed -r -f b.sed 
xy-uv>ab-cd-ed-ef-gh< 
xy-uv>ab cd ed ef gh<

This is much easier with awk than sed as you can do substitutions on given fields: 使用awksed容易得多,因为您可以在给定字段上进行替换:

$ awk '{gsub(/-/," ",$2)}1' FS='>' OFS='>' file
xy-uv>ab cd ed ef gh<

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

sed -r ':a;s/(>[^<]*)-([^<]*<)/\1 \2/;ta' file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM