简体   繁体   English

sed模式以匹配和替换

[英]Sed pattern to match and replace

How can I write a sed expression, which looks through a line to match 我该如何写一个sed表达式,该表达式通过一行来匹配

Id int

and change to 并更改为

Id string

this will be the only content in that line (nothing other than, Id int) and should not alter other lines. 这将是该行中的唯一内容(Id int除外),并且不应更改其他行。

I tried with something along the lines 我尝试了一些方法

find . -type f -print0 | xargs -0  sed -i '' 's~^\([[:space:]]*\)"Id"[[:space:]]*"int"[:space:]]*$~\1"Id string"~g'

But the reg exp is wrong. 但是reg exp是错误的。

Thanks. 谢谢。

Edit: 编辑:

To clarify further: There are spaces (inconsistent) before Id , between Id and int . 为了进一步说明:在Id之前,在Idint之间存在空格(不一致)。 So, needs to match [[:space:]]* , instead of tab or expressions like s/^Id int$ 因此,需要匹配[[:space:]] *,而不是制表符或s/^Id int$s/^Id int$表达式

so the lines to match can be 所以匹配的线可以是

   Id int
Id   int
  Id      int

It can be replaced with 可以替换为

Id string
Id string
Id string

means, no need to preserve the number of spaces 意味着,无需保留空格数

I believe the following will do what you want: 我相信以下将满足您的要求:

sed 's/^Id int$/Id string'

The ^ means start of the line , and $ means end of the line , so we restrict the changes to lines which only contain Id int and not lines like I like Id int . ^意味着该行的开始 ,而$意味着该行的结束 ,所以我们限制更改为只包含行Id int而不是线,如I like Id int

Update following OP clarification: 根据OP的说明进行更新:

If you want to match the cases where there is varying whitespace, and preserve this whitespace then you could use: 如果要匹配存在不同空格的情况,并保留此空格,则可以使用:

sed 's/^\([[:space:]]*\)Id\([[:space:]]+\)int\([[:space:]]*\)$/\1Id\2string\3/'

This will preserve the whitespace before Id , between the Id and int , and after int . 这将保留空白之前Id ,之间Idint ,经过int If you don't want to preserve the whitespace between the words or after thet last word, remove the group match parameters \\2 and \\3 from the sed experession. 如果不想保留单词之间或最后一个单词之后的空白,请从sed表达式中删除组匹配参数\\2\\3

Easier with awk: 使用awk更轻松:

awk '$2=="int"{$2="string"}1'

And potentially easier to tweak to your actual needs. 并且可能更容易调整您的实际需求。

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

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