How to write to a file using awk to find a string in between ( ); and add a printline after ; to print the string found?

倾然丶 夕夏残阳落幕 提交于 2019-12-06 08:04:51

You can try the following bash script:

#! /bin/bash

files=(*.txt)

for ((i=0; i<${#files[@]}; i++)) ; do
    file="${files[$i]}"
    awk -f f.awk "$file" > "${file}.mod"
done

where f.awk is:

{
    gsub(/\([^)]*\)/,"&; printf&")
    print
}

Note that this will not work for nested parenthesis, like sqrt(4+2*(x+y)).. (If that is needed I can try to update my answer.).

Given example file input.txt:

x=7;
sqrt(x+5*4); sqrt(x*x); 
i=3;
a=2+sqrt(8);

Running: awk -f f.awk input.txt gives:

x=7;
sqrt(x+5*4); printf(x+5*4); sqrt(x*x); printf(x*x); 
i=3;
a=2+sqrt(8); printf(8);

For Gnu Awk, I recommend the following Awk resource: http://www.gnu.org/software/gawk/manual/gawk.html

awk is certainly a fine tool, but why not stretch a little? If you are willing to discard the whitespace inside the parentheses, try:

cat << 'EOF' - input-file | m4
divert(-1)
define(`sqrt',`divert(1)'$1
`divert(-1)')
EOF

That should print out every string that appears within a call to sqrt in the file named input-file. This will not evaluate the strings, but it's not clear to me if you want that.

The primary advantage of this solution is that it will work well with nested parentheses. That is, lines of the form sqrt( foo( bar( x + y ))) will correctly print foo( bar( x + y )), and that will be difficult to parse correctly with awk. The primary disadvantage is that it requires correct syntax on the input (unbalanced parentheses will cause problems).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!