简体   繁体   中英

Add timestamp for each line on the df output command?

I would like to add the date for each lines of the df output command.

I try:

df -m | awk '{print `date +%Y-%m`";"$1";"$2";"$3 }'

But it doesn't work...

Any idea?

Here is an alternative:

df -m | awk '{print strftime("%Y-%m"), $0}'

And here is the output from the command above:

$ df -m | awk '{print strftime("%Y-%m"), $0}'
2019-10 Filesystem                     1M-blocks   Used Available Use% Mounted on
2019-10 devtmpfs                            9852      0      9852   0% /dev
2019-10 tmpfs                               9871    132      9740   2% /dev/shm
2019-10 tmpfs                               9871      2      9869   1% /run
2019-10 /dev/mapper/fedora_canvas-root     50141  14731     32834  31% /
2019-10 tmpfs                               9871      1      9871   1% /tmp
2019-10 /dev/sda5                            976    243       667  27% /boot
2019-10 /dev/mapper/fedora_canvas-home   1277155 217435    994777  18% /home
2019-10 tmpfs                               1975     63      1912   4% /run/user/1000
$ 

And here is an alternative version, printing just the 3 columns you wanted on the OP:

df -m | awk '{print strftime("%Y-%m"), $1, $2, $3}' | column -t

And the corresponding output:

$ df -m | awk '{print strftime("%Y-%m"), $1, $2, $3}' | column -t
2019-10  Filesystem                      1M-blocks  Used
2019-10  devtmpfs                        9852       0
2019-10  tmpfs                           9871       132
2019-10  tmpfs                           9871       2
2019-10  /dev/mapper/fedora_canvas-root  50141      14731
2019-10  tmpfs                           9871       1
2019-10  /dev/sda5                       976        243
2019-10  /dev/mapper/fedora_canvas-home  1277155    217435
2019-10  tmpfs                           1975       63
$

A Perl solution.

df -m | perl -MPOSIX=strftime -alpe '$_ = strftime("%Y-%M ", localtime) . "@F[0..2]"'

Command line options:

  • -M: Load the strftime() function from the POSIX module
  • -a: Autosplit the input records on whitespace into @F
  • -l: Remove newlines from input and add them to output
  • -p: Put each input record into $_ , execute code and then print $_
  • -e: Run this code for each input record

The code updates $_ by concatenating the date ( strftime("%Y-%M ", localtime) ) with the first three columns ( @F[0.. 2] ) of the input record.

You may use this way:

df -m | awk -v dt=$(date "+%Y-%m") '{print dt "::", $0}'

We use -v dt=$(date "+%Y-%m") to execute date command in shell and pass it to awk in an argument dt .

If you want only first 3 columns from df command output then use:

df -m | awk -v dt=$(date "+%Y-%m") '{print dt, $1, $2, $3}'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM