如何在shell脚本中实现awk的printf输出重定向至文件?
需求与问题
我需要在脚本的104-106行实现:当执行./sample23.sh -o samples.bin(即选择-o选项)时,将printf命令的输出重定向到文件。相关代码片段如下:
oPrint="3" if (oParamPassed && oPrint == 3) { printf("Total Samples in %s:\t%d\nTotal Samples Processed:\t%d\n", baseFileName, lines+1, last+1) }
我尝试了以下方法均未成功:
- 在脚本的awk部分尝试多种
printf语句输出重定向方式,但都无效; - 在脚本末尾通过bash重定向整个awk脚本的输出,导致
-t选项与-o选项行为一致;
解决方案
参考@tshiono的方案,我添加了精确到秒的日期以避免文件覆盖,具体修改如下:
在bash部分添加:
[[ $oParamPassed = "true" ]] && { exec > outfile-$(date +%m-%d-%Y.%H:%M:%S); }
同时将awk中的对应代码块修改为:
oPrint="3" if (oParamPassed && oPrint == 3) { printf outfile }
执行结果
执行命令./sample22.sh -o samples.bin后,查看输出文件末尾内容:
tail -9 outfile-08-29-2022.13:31:48 Sample 374364: 0x3403 0x0d03 0x4403 0x7803 Sample 374365: 0xee03 0x2c03 0x4503 0xf204 Sample 374366: 0x1a03 0xba03 0x4103 0x9c03 Sample 374367: 0x6103 0x3903 0x4703 0xf703 Sample 374368: 0x1603 0xf403 0x3403 0x7f03 Sample 374369: 0x7003 0x9903 0x3503 0x3503 Sample 374370: 0x1303 0x4b03 0x3703 0x8f03 Total Samples in samples.bin: 374371 Total Samples Processed: 374371
内容的提问来源于stack exchange,提问作者puppet_master
相关产品推荐
相关产品推荐

