awk中執行Linux命令的兩種方式


在使用awk處理內容時,有時會按行執行Linux命令,下面介紹兩種執行Linux命令方式。

方式一

用system():

[root@localhost shell_script]# awk 'BEGIN {system("pwd")}'
/root/shell_script
[root@localhost shell_script]#

test.log文件:

[root@localhost shell_script]# cat test.log 
pwd
ls
which sh
[root@localhost shell_script]#

按文件行作為輸入執行:

$0 表示一行數據

[root@localhost shell_script]# awk '{print "執行命令:"$0; system($0); print "\r"}' test.log
執行命令:pwd
/root/shell_script

執行命令:ls
awk_system.sh  test.log

執行命令:which sh
/usr/bin/sh

[root@localhost shell_script]#

拼接命令:

[root@localhost shell_script]# echo "sh601236" | awk '{cmd = "curl -X GET http://hq.sinajs.cn/list="$0; system(cmd);}'
var hq_str_sh601236="紅塔證券,19.930,20.320,19.150,19.930,18.710,19.150,19.160,41190044,791608359.000,198000,19.150,53300,19.140,60100,19.130,74200,19.120,24100,19.110,50500,19.160,28500,19.170,18300,19.180,15500,19.190,59300,19.200,2020-06-29,15:00:00,00,";
[root@localhost shell_script]#

 

方式二

借助|sh命令:
[root@localhost shell_script]# echo "pwd" | sh
/root/shell_script
[root@localhost shell_script]# cat test.log | sh
/root/shell_script
awk_system.sh  test.log
/usr/bin/sh
[root@localhost shell_script]#

print

[root@localhost shell_script]# awk 'BEGIN {print "pwd" | "sh"}'
/root/shell_script
[root@localhost shell_script]#
[root@localhost shell_script]# echo "pwd" | awk '{print $0 | "sh"}'
/root/shell_script
[root@localhost shell_script]#
[root@localhost shell_script]# awk '{print "執行命令:"$0; print $0 | "sh"; print "\r"}' test.log
執行命令:pwd

執行命令:ls

執行命令:which sh

/root/shell_script
awk_system.sh  test.log
/usr/bin/sh
[root@localhost shell_script]#


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM