使用正则表达式和 Unix 工具匹配不在任何注释内的单词

问题描述 投票:0回答:3

如何使用 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
regex awk sed
3个回答
4
投票

编辑:考虑到新的限制,并假设您的评论!总是用空格封装,而引用的!则不是,对 Tripleee 的答案进行微小的更改就可以了:
将封装空间包含在字段分隔符中。

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

 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

3
投票

这个怎么样?

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

使用

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


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
© www.soinside.com 2019 - 2024. All rights reserved.