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

时间:2016-01-28 05:51:24

标签: bash shell csv awk top-command

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

 #!/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

这是我的shell脚本 top.sh

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 命令执行相同的操作,但它对我不起作用!我编辑了这样的代码 -

<div class="pc-img" ></div>
<div class="mobile-img" ></div>

2 个答案:

答案 0 :(得分:1)

您的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

答案 1 :(得分:0)

在这一行:

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
相关问题