首页 > 解决方案 > 在 shell 脚本中打印数据时格式失败

问题描述

你能帮我看看我用来建立日志的这段代码吗?

##Log construction
printf $timestamp >> $temp"logs.txt"
printf "        " >> $temp"logs.txt"
printf $filekey >> $temp"logs.txt"
cat $temp$filekey"_content.txt" >> $temp"logs.txt"

这段代码进入了一个 bash 脚本,其中包含一个循环,该循环运行 N 次,具体取决于某个文本文件的行数(在此示例中,文本文件只有 2 行),问题是打印结果的顺序logs.txt 仅在此脚本第一次运行时就可以了,如下所示:

2020_09_04--10:09:41    myhost1.ec2.local        records_found         62
2020_09_04--10:09:41    myhost2.ec2.local        records_found         62

下次脚本运行时,它会修改 logs.txt 文件,但会在发现破坏日志格式的最后一个文本之后粘贴结果,如下所示:

2020_09_04--10:09:41    myhost1.ec2.local        records_found         62
2020_09_04--10:09:41    myhost2.ec2.local        records_found         622020_09_04--10:10:21    myhost1.ec2.local        records_found         64
2020_09_04--10:10:21     myhost2.ec2.local        records_found         64

预期结果是:

    2020_09_04--10:09:41    myhost1.ec2.local        records_found         62
    2020_09_04--10:09:41    myhost2.ec2.local        records_found         62
    2020_09_04--10:10:21    myhost1.ec2.local        records_found         64
    2020_09_04--10:10:21    myhost2.ec2.local        records_found         64

非常感谢任何帮助。谢谢。-亚历克斯。

标签: bashshell

解决方案


推荐阅读