如何使用awk进行查找替换并计算?

如何使用awk进行查找替换并计算?

0.2rem我在一个包含or 的文件夹下有几个 CSS 文件0.5rem 0.6rem,现在我希望它们全部除以 2,成为0.1rem0.25rem, 0.3rem。我如何使用awkorsedgawk来完成此任务?

我尝试了以下命令但没有成功:

find . -name "*.css" | xargs gawk -i inplace '{gsub(/([0-9\.]+)rem/, "(\\1 * 0.5)rem"); print $0}'

答案1

不确定sed/gawk,但这里有一个perl

$ echo '0.2rem or 0.5rem 0.6rem' | perl -pe 's/\d+(\.\d+)?(?=rem)/$&*0.5/ge'
0.1rem or 0.25rem 0.3rem
  • \d+(\.\d+)?将数字与可选的小数部分匹配
    • (?=rem)确保数字后面跟着rem
  • $&*0.5将数字乘以0.5-e修饰符允许在替换部分使用 Perl 代码而不是字符串


应用于文件:

find . -name "*.css" -exec perl -i -pe 's/\d+(\.\d+)?(?=rem)/$&*0.5/ge' {} +

也可以看看:为什么循环查找的输出是不好的做法?

答案2

find+ GNUawk解决方案:

find . -type f -name "*.css" -exec gawk -i inplace \
'{ for (i=1; i<=NF; i++) 
       if ($i ~ /^[0-9]+\.[0-9]+rem/) { v=$i/2; sub(/^[0-9]+\.[0-9]+/, "", $i); $i=v $i } 
 }1' {} \;

答案3

对于gawk,您可以将RS其视为正则表达式,并且事实上,该处RT包含 所匹配的内容RS。所以:

find . -name '*.css' -type f -exec \
  gawk -i /usr/share/awk/inplace.awk -v RS='[0-9.]*[0-9]rem' -v ORS= 'RT{$0=$0 RT/2 "rem"};1' {} +

不使用-i inplaceas尝试首先从当前工作目录gawk加载inplace扩展(asinplace或),有人可能已经在其中植入了恶意软件。随系统提供的扩展inplace.awk的路径可能会有所不同,请参阅输出inplacegawkgawk 'BEGIN{print ENVIRON["AWKPATH"]}'

答案4

gawk -i inplace '
{
    for(i = 1; i <= NF; i++) {
        if($i ~ /[0-9]+(\.[0-9]+)?rem/) 
            $i = $i / 2 "rem"            
    }
    print
}' file_*

程序执行前的3个文件内容

tail -n +1 -- file_*命令一次显示多个文件内容。

$ tail -n +1 -- file_*

==> file_1 <==
0.2rem lorem ipsum 0.5rem
Lorem 0.2rem ipsum dolor sit amet, 0.5rem consectetur adipiscing elit magna aliqua.
Lorem ipsum 0.8rem dolor sit amet, 6rem consectetur 2rem adipiscing elit magna aliqua.
0.2rem lorem ipsum 0.5rem

==> file_2 <==
0.2rem lorem ipsum 0.5rem
Lorem 0.2rem ipsum dolor sit amet, 0.5rem consectetur adipiscing elit magna aliqua.
0.2rem lorem ipsum 0.5rem
Lorem ipsum 0.8rem dolor sit amet, 6rem consectetur 2rem adipiscing elit magna aliqua.

==> file_3 <==
0.2rem lorem ipsum 0.5rem
Lorem 0.2rem ipsum dolor sit amet, 0.5rem consectetur adipiscing elit magna aliqua.
Lorem ipsum 0.8rem dolor sit amet, 6rem consectetur 2rem adipiscing elit magna aliqua.

程序执行后的3个文件内容

$ tail -n +1 -- file_*

==> file_1 <==
0.1rem lorem ipsum 0.25rem
Lorem 0.1rem ipsum dolor sit amet, 0.25rem consectetur adipiscing elit magna aliqua.
Lorem ipsum 0.4rem dolor sit amet, 3rem consectetur 1rem adipiscing elit magna aliqua.
0.1rem lorem ipsum 0.25rem

==> file_2 <==
0.1rem lorem ipsum 0.25rem
Lorem 0.1rem ipsum dolor sit amet, 0.25rem consectetur adipiscing elit magna aliqua.
0.1rem lorem ipsum 0.25rem
Lorem ipsum 0.4rem dolor sit amet, 3rem consectetur 1rem adipiscing elit magna aliqua.

==> file_3 <==
0.1rem lorem ipsum 0.25rem
Lorem 0.1rem ipsum dolor sit amet, 0.25rem consectetur adipiscing elit magna aliqua.
Lorem ipsum 0.4rem dolor sit amet, 3rem consectetur 1rem adipiscing elit magna aliqua.

相关内容