使用sed和awk替换正则表达式

时间:2022-06-19 10:32:32

I'm trying to replace first, second and third %f with a b and c respectively using sed and awk.

我试图用sed和awk分别用b和c替换第一,第二和第三%f。

(51.7296373326*%f)+(41.7319764456*%f)+(-193.993966414*%f)

This is what i've tried

这就是我尝试过的

sed "s|(51.7296373326*%f)|(51.7296373326*a)|g" dump1.txt  

The values are not constant..

值不是常数..

1 个解决方案

#1


1  

I guess you meant sed or awk.

我想你的意思是sed或awk。

awk 'BEGIN{a[++i]="a";a[++i]="b";a[++i]="c"}
     {for(x=1;x<=i;x++)sub(/%f/,a[x])}7' file

if the replacement list is big, like a-z, you can put them in a file, first load it into array a instead of loading them in BEGIN block.

如果替换列表很大,比如a-z,你可以将它们放在一个文件中,首先将它加载到数组a中,而不是将它们加载到BEGIN块中。

Note, the codes could be optimized by checking the return value of sub, if 0, break.

注意,可以通过检查sub的返回值来优化代码,如果为0,则为break。

#1


1  

I guess you meant sed or awk.

我想你的意思是sed或awk。

awk 'BEGIN{a[++i]="a";a[++i]="b";a[++i]="c"}
     {for(x=1;x<=i;x++)sub(/%f/,a[x])}7' file

if the replacement list is big, like a-z, you can put them in a file, first load it into array a instead of loading them in BEGIN block.

如果替换列表很大,比如a-z,你可以将它们放在一个文件中,首先将它加载到数组a中,而不是将它们加载到BEGIN块中。

Note, the codes could be optimized by checking the return value of sub, if 0, break.

注意,可以通过检查sub的返回值来优化代码,如果为0,则为break。