如何用 bash/awk 将每个文件的日期显示为每行的第一个元素?

How to display the date of each file as the first element of each lines with bash/awk?

我有 7 个 txt 文件,它们是 AIX 7.2 上 df -m 命令的输出。

我只需要为一个文件系统保留第一列和第二列。所以我这样做了:

cat *.txt | grep hd4 | awk '{print ","}' > test1.txt

输出为:

/dev/hd4,384.00
/dev/hd4,394.00
/dev/hd4,354.00
/dev/hd4,384.00
/dev/hd4,484.00
/dev/hd4,324.00
/dev/hd4,384.00

每个文件都是从 crontab 创建的,它们的文件名是:

df_command-2019-09-03-12:50:00.txt
df_command-2019-08-28-12:59:00.txt
df_command-2019-08-29-12:51:00.txt
df_command-2019-08-30-12:52:00.txt
df_command-2019-08-31-12:53:00.txt
df_command-2019-09-01-12:54:00.txt
df_command-2019-09-02-12:55:00.txt

我只想在文件名上保留日期,我可以做到:

test=df_command-2019-09-03-12:50:00.txt
echo $test | cut -d'-' -f2,3,4

输出:

2019-09-03

但我想将每个日期作为我 test1.txt :

每行的第一个元素
2019-08-28,/dev/hd4,384.00
2019-08-29,/dev/hd4,394.00
2019-08-30,/dev/hd4,354.00
2019-08-31,/dev/hd4,384.00
2019-09-01,/dev/hd4,484.00
2019-09-02,/dev/hd4,324.00
2019-09-03,/dev/hd4,384.00

你有什么想法吗?

这个awk可能会做:

awk '/hd4/ {split(FILENAME,a,"-");print a[2]"-"a[3]"-"a[4]","","}' *.txt > test1.txt
  • /hd4/ 查找符合 hd4
  • 的行
  • split(FILENAME,a,"-") 将文件名拆分为数组 a 拆分为 -
  • print a[2]"-"a[3]"-"a[4]","","打印年月日,字段1,字段2
  • > test1.txt 到文件 test1.txt

日期输出文件:dates.txt

2019-08-20
2019-08-08
2019-08-01

文件系统数据fsys.txt

/dev/hd4,384.00 
/dev/hd4,394.00 
/dev/hd4,354.00

paste 可用于将文件附加为列。使用 -d 指定逗号作为分隔符。

paste -d ',' dates.txt fsys.txt