如何在文件上找到时间戳,然后将其作为第一行回显到文件内容中?

Hap*_*ays 4 command-line bash sed

我正在尝试调整以下命令:

 stat -c %y test.txt | sed 's/^\([0-9\-]*\)/\1/'
Run Code Online (Sandbox Code Playgroud)

这将返回以下信息:

 2016-08-03 14:52:24.000000000
Run Code Online (Sandbox Code Playgroud)

我需要调整它以排除“.000000000”。我尝试了几种不同的选择,但似乎无法正确解决。最终,我需要获取从上述命令中提取的时间戳,并将其作为第一行回显到文件中。

我以这个命令为例,它似乎正确地在文件顶部添加了一个新行:

   sed -i '1s/^/this should be a date\n/' test.txt
Run Code Online (Sandbox Code Playgroud)

如何组合这两个命令?

Ser*_*nyy 5

像这样:

( stat -c %y test_file.txt | awk -F '.' '{print $1}' ; cat test_file.txt  ) > /tmp/temp_file && mv /tmp/temp_file test_file.txt
Run Code Online (Sandbox Code Playgroud)

这是一个小演示:

$> echo "Hello World" > test_file.txt
$> ( stat -c %y test_file.txt | awk -F '.' '{print $1}' ; cat test_file.txt  ) > /tmp/temp_file &&                       
> mv /tmp/temp_file test_file.txt
$> cat test_file.txt                                                                                                     
2016-08-03 09:24:27
Hello World
Run Code Online (Sandbox Code Playgroud)

解释:

  • 我们在子shell中得到时间戳和文件内容,用括号表示 (...)
  • stat -c %y test_file.txt | awk -F '.' '{print $1}' 修剪时间戳
  • cat test_file.txt 读取文件内容。
  • 结果文本是时间戳加上文件中的任何内容,被重定向到 /tmp/temp_file
  • 最后我们用以下内容替换原始文件 /tmp/temp_file