How can I collapse this bash command line into an awk statement?

谁都会走 提交于 2020-01-04 09:16:08

问题


I've created an awk script and use it like this:

# grep -E "[PM][IP][DO][:S]" file.txt | awk-script

How can I modify the awk script to include the effort of the grep command (which is searching for either "PID:" or "MPOS"?

awk-script is:

#!/usr/bin/awk -f
/Sleeve/  {
        printf("%8d, %7d, %7.2f, %7.2f, %7.2f\n", $5, $6, $7, $30, $31)
}
/Ambient/ {
        printf("%8d, %7d,,,, %7.2f, %7.2f\n", $5, $6, $7, $8)
}
/MPOS:/ {
        printf("%8d, %7d,,,,,, %5d, %5d\n", $4, $5, $2, $3)
}

回答1:


If you just want to search for PID: or MPOS, you can say that if you don't find them in the line, you want to skip following rules:

#!/usr/bin/awk -f

!/PID:|MPOS/ { 
        next 
}

/Sleeve/  {
        printf("%8d, %7d, %7.2f, %7.2f, %7.2f\n", $5, $6, $7, $30, $31)
}
/Ambient/ {
        printf("%8d, %7d,,,, %7.2f, %7.2f\n", $5, $6, $7, $8)
}
/MPOS:/ {
        printf("%8d, %7d,,,,,, %5d, %5d\n", $4, $5, $2, $3)
}



回答2:


I tried litb's answer in busybox (on Ubuntu in Bash) and it worked for me. For testing, I used the following shebang to match where I have symbolic links to busybox:

#!/home/username/busybox/awk -f

And ran the test using:

./awk-script file.txt

I also ran the test under busybox sh (with PATH=/home/username/busybox:$PATH although not necessary for this) and it worked there.

When you say "I still have grief." what does that mean? Are you getting error messages or incorrect results?

By the way, unless you're searching for all permutations of the characters, you can do your grep like this:

grep -E "(PID:|MPOS)" file.txt


来源:https://stackoverflow.com/questions/1510175/how-can-i-collapse-this-bash-command-line-into-an-awk-statement

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