简体   繁体   English

如何通过 sed 或 awk 匹配和替换匹配后的字符串

[英]How to match and replace string following the match via sed or awk

I have a file which I want to modify into a new file using cat.我有一个文件,我想使用 cat 将其修改为一个新文件。 So the file contains lines like:所以该文件包含如下几行:

name "myName"
place "xyz" 

and so on....等等....

I want these lines to be changed to我希望将这些行更改为

name "Jon"
place "paris"

I tried to do it like this but its not working:我试图这样做,但它不工作:

cat originalFile | sed 's/^name\*/name "Jon"/' > tempFile 

I tried using all sorts of special characters and it did not work.我尝试使用各种特殊字符,但没有奏效。 I am unable to recognize the space characters after name and then "myName".我无法识别名称后的空格字符,然后是“myName”。

You may match the rest of the line using .* , and you may match a space with a space, or [[:blank:]] or [[:space:]] :您可以使用.*匹配行的其余部分,并且可以将空格与空格匹配,或者[[:blank:]][[:space:]]

sed 's/^\(name[[:space:]]\).*/\1"Jon"/;s/^\(place[[:space:]]\).*/\1"paris"/' originalFile > tempFile

Note there are two replace commands here joined with s semicolon.注意这里有两个用 s 分号连接的替换命令。 The first parts are wrapped with a capturing group that is necessary because the space POSIX character class is not literal and in order to keep it after replacing the \\1 backreference should be used (to insert the text captured with Group 1).第一部分用捕获组包装,这是必要的,因为空间 POSIX 字符类不是文字,为了在替换后保留它,应该使用\\1反向引用(插入用组 1 捕获的文本)。

See the online demo :请参阅在线演示

s='name "myName"
place "xyz"'
sed 's/^\(name[[:space:]]\).*/\1"Jon"/;s/^\(place[[:space:]]\).*/\1"paris"/' <<< "$s"

Output:输出:

name "Jon"
place "paris"

An awk alternative:一个awk替代方案:

awk '$1=="name"{$0="name \"Jon\""} $1=="place"{$0="place \"paris\""} 1' originalFile

It will work when there're space(s) before name or place .nameplace之前有空格时,它会起作用。
It's not regex match here but just string compare.这里不是正则表达式匹配,而是字符串比较。
awk separates fields by space characters which including \\n or awk用空格字符分隔字段,其中包括\\n. .

Append > tempFile to it when the results seems correct to you.当结果对您来说是正确的时,将> tempFile附加到它。

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

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