【发布时间】:2021-04-30 10:36:25
【问题描述】:
我正在编写一个用于格式化 Fortran 源代码的脚本。 简单的格式,比如所有关键字都是大写或小写等。 这是主要命令
sed -i -e "/^\!/! s/$small\s/$cap /gI" $filein
它将每个关键字 $small(后跟一个空格)替换为关键字 $caps。并且仅当该行不以“!”开头时才会发生替换。 它做它应该做的。问题:
如果“!”,如何避免替换在一行的中间遇到。 或者更一般地说,如何替换所有地方的模式,但不是在特定符号之后,它可以在行首或其他地方。
例子:
Program test ! It should not change the next program to caps
! Hi, is anything changing here? like program ?
This line does not have any key words
This line has Program and not exclamation mark.
“程序”是一个关键字。运行脚本后的结果是:
PROGRAM test ! It should not change the next PROGRAM to caps
! Hi, is anything changed here? like program ?
This line does not have any key words
This line has PROGRAM and not exclamation mark.
我想要:
PROGRAM test ! It should not change the next program to caps
! Hi, is anything changed here? like program ?
This line does not have any key words
This line has PROGRAM and not exclamation mark.
到目前为止,我还没有找到一个很好的解决方案,希望可以使用 sed 命令来解决问题。
【问题讨论】:
-
听起来像XY Problem;我假设更大的图景会看到很多很多这些类型的更改,在这种情况下,我想知道花一些时间在顶层设计上是否有意义,例如语法(重新)解析器,或者一个脚本(
awk?perl?)来处理这些变化的库......而不是目前看起来像100个单独的sed调用......? -
GNU awk 怎么样?试试
awk -i inplace -v small="$small" -v cap="$cap" 'BEGIN{IGNORECASE=1;FS=OFS="!"} {gsub(small, cap, $1)}1' $filein,见ideone.com/ugd5JE -
那么,ideone.com/lM4fZC 对你有用吗?
-
注:
Program和program不一样,那么 $small 变量是否代表正则表达式?