在 CSV 文件的每一行末尾添加时间戳

Add timestamp to the end of each line of a CSV file

我正在尝试使用 shell 脚本获取 top 命令的前 5 行。这是我的 shell 脚本的输出。

PID,USER,PR,NI,VIRT,RES,SHR,S,%CPU,%MEM,TIME+,COMMAND
3983,arun,20,0,1874616,500356,24132,R,47.6,10.3,53:19.92,gnome-shell
11,root,20,0,0,0,0,R,4.8,0.0,0:22.51,rcuos/0
2016,root,20,0,219396,44408,9120,S,4.8,0.9,9:53.96,Xorg
12081,arun,20,0,2689552,304132,7076,S,4.8,6.3,13:36.17,java
1,root,20,0,141660,5336,2940,S,0.0,0.1,0:08.40,systemd
3983,arun,20,0,1874616,500356,24132,R,56.2,10.3,53:20.99,gnome-shell
2016,root,20,0,219396,44408,9120,R,18.8,0.9,9:54.17,Xorg
4969,arun,20,0,1287084,162948,48472,S,12.5,3.4,5:39.99,chrome
16108,arun,20,0,130020,1692,1172,R,6.2,0.0,0:00.01,top
1,root,20,0,141660,5336,2940,S,0.0,0.1,0:08.40,systemd
3983,arun,20,0,1874616,500356,24132,R,43.8,10.3,53:24.56,gnome-shell
4969,arun,20,0,1275992,147104,32424,S,37.5,3.0,5:41.10,chrome
1,root,20,0,141660,5336,2940,S,0.0,0.1,0:08.40,systemd
2,root,20,0,0,0,0,S,0.0,0.0,0:00.06,kthreadd
3,root,20,0,0,0,0,S,0.0,0.0,0:04.93,ksoftirqd/0

这是我的 shell 脚本 top.sh

 #!/bin/bash
echo "started.."
top -b -n 3 | sed -n '7,1{s/^ *//;s/ *$//;s/  */,/gp;};12q' >> out.txt

while [ true ]; do
  sleep 5
  echo "inside loop.."
  top -b -n 3 | sed -n '8,12{s/^ *//;s/ *$//;s/  */,/gp;};12q' >> out.txt
done

现在,我需要在每行的末尾添加时间戳。我尝试使用 awk 命令来做同样的事情,但它对我不起作用!我已经像这样编辑了我的代码 -

#!/bin/bash
    echo "started.."
    t= =$(date +"%T")

    top -b -n 3 | sed -n '7,1{s/^ *//;s/ *$//;s/  */,/gp;};12q' >> out.txt
    awk -F, '{$(NF+1)="TIME";}1' OFS=, out.txt    

    while [ true ]; do
      sleep 5
      t=$(date +"%T")
      echo "inside loop.."
      top -b -n 3 | sed -n '8,12{s/^ *//;s/ *$//;s/  */,/gp;};12q' >> out.txt
      awk -F, '{$(NF+1)=$t;}1' OFS=, file
    done

这一行:

awk -F, '{$(NF+1)=$t;}1' OFS=, file

您正在使用单引号内的 shell 变量 $t,因此它不会被展开。使用 -v 语法将 shell 变量传递给 awk:

awk -F, -v OFS=, -v t="$t" '{$(NF+1)=t;}1'  file

您的 Awk 命令将 运行 遍历整个文件(或者在第二个实例中是整个不相关或不存在的文件)并打印到标准输出。修复覆盖输入文件的命令会将时间戳添加到已有时间戳的行中。无论如何,您想将日期戳添加内联到将新数据附加到文件的命令中,而不是将更多日期戳添加到整个文件。

sed 脚本已经执行了一些替换。考虑时间戳也很简单。您需要使用双引号而不是单引号,以便 shell 扩展变量的值。

#!/bin/bash

t=$(date +"%T")   #### Syntax error fixed
top -b -n 3 |
sed -n -e '7!b;s/^ *//' -e "s/ *$/,$t/" -e 's/  */,/gp;q' >> out.txt
#### ^sed script refactored; only work on line 7, not until 12

while true; do   #### Wacky syntax fixed
  sleep 5
  t=$(date +"%T")
  top -b -n 3 |
  sed -n -e '8,12{s/^ *//' -e "s/ *$/,$t/" -e 's/  */,/gp;};12q' >> out.txt
done