匹配任何注释中没有正则表达式和Unix工具的单词

时间:2014-05-24 12:11:40

标签: regex sed

如何使用sed,awk或其他内容来匹配单词type的出现,其中包含type的行在出现之前没有任何!出现type的?然后用其他东西替换type

所以我要求匹配在Fortran 90评论中没有出现的单词type的出现。

修改

  • !之前,同一行上多次出现的单词也应该被替换。
  • !在单引号或双引号内不起评论字符的作用,因此"!"'!'"'!'"后的出现也应该被替换。我认为这使任务变得非常复杂。
  • 不应更改包含type的字词,例如footype

可能的解决方案:

awk -F '!' -v OFS='!' '{ gsub("\\<type\\>", "replacement", $1) } 1' file

似乎解决了这个问题,但它仍然无法处理!内部引号。

最小例子

  type = 2 +type
  type type 
  lel = "!" type
  lel = '!' type
  lel = "'!'" type
  ! type=2
type
footype

应该变成:

  replacement = 2 +replacement
  replacement replacement 
  lel = "!" replacement
  lel = '!' replacement
  lel = "'!'" replacement
  ! type=2
replacement
footype

3 个答案:

答案 0 :(得分:4)

编辑:鉴于新约束,并假设您的评论!空格始终用空格封装而且引用的内容不是,对tripleee进行微小改动&# 39;答案是有效的:
在字段分隔符中包含封装空格。

测试用例:(随机出现的条件)

 odd= (/ '!'1,3,5,7,9 /)  ! array assignment
 even=(/ 2,4,6,8,10 /) ! array assignment
 a=1"'!'"write         ! testing: write
 b=2
 c=a+b+e      ! element by element assignment
 c(odd)=c(even)-1  ! can use arrays of indices on both sides
 d=sin(c)     ! element by element application of intrinsics
 write(*,*)d
 write(*,*)abs(d)  ! many intrinsic functions are generic 
 write(*,*)abs(d)write  ! many intrinsic functions are generic
 write(c=a+b+e)      ! element by write element assignment
 write(*,*)abs("!"d)write  ! many intrinsic functions are generic

命令和输出:

$ awk -F ' ! ' -v OFS=' ! ' '{ gsub("write", "replacement", $1) } 1' type

 odd= (/ '!'1,3,5,7,9 /)  ! array assignment
 even=(/ 2,4,6,8,10 /) ! array assignment
 a=1"'!'"replacement         ! testing: write
 b=2
 c=a+b+e      ! element by element assignment
 c(odd)=c(even)-1  ! can use arrays of indices on both sides
 d=sin(c)     ! element by element application of intrinsics
 replacement(*,*)d
 replacement(*,*)abs(d)  ! many intrinsic functions are generic 
 replacement(*,*)abs(d)replacement  ! many intrinsic functions are generic
 replacement(c=a+b+e)      ! element by write element assignment
 replacement(*,*)abs("!"d)replacement  ! many intrinsic functions are generic

答案 1 :(得分:3)

这个怎么样?

awk -F '!' -v OFS='!' '{ gsub("type", "replacement", $1) } 1' file

使用-F '!'将字段分隔符转换为感叹号;所以第一个字段是第一个分隔符之前的任何文本,我们只在此字段中全局替换type。 (唯一的1是用于打印所有行的简写习惯用法; OFS是输出字段分隔符,不需要单独设置以保留输入字段分隔符。)

答案 2 :(得分:1)

我在这里使用awk

测试位置
cat file
This!hastypeinit
her are more type do
thistypemay also go
what type ! i have here
There must ! this type be

awk 'index($0,"!")>index($0,"type") || !index($0,"!") {sub(/type/,"****")}1' file
This!hastypeinit
her are more **** do
this****may also go
what **** ! i have here
There must ! this type be

或使用与Sintrinsic相同的regex

awk '/^[^!]*type/ {sub(/type/,"****")}1' file
This!hastypeinit
her are more **** do
this****may also go
what **** ! i have here
There must ! this type be