Home > Net >  Append number of days since the date in the line to each line in the file using Bash
Append number of days since the date in the line to each line in the file using Bash

Time:01-15

I have a file that consists of the following...

false|aaa|user|aaa001|2014-12-11|
false|bbb|user|bbb||
false|ccc|user|ccc|2021-10-19|
false|ddd|user|ddd|2018-11-16|
false|eee|user|eee|2020-06-02|

I want to use the date in the 5th column to calculate the number of days from the current date and append it to each line in the file.

The end result would be a file that looks like the following, assuming the current date is 1/13/2022...

false|aaa|user|aaa001|2014-12-11|2590
false|bbb|user|bbb||
false|ccc|user|ccc|2021-10-19|86
false|ddd|user|ddd|2018-11-16|1154
false|eee|user|eee|2020-06-02|590

Some lines in the file will not contain a date value (which is expected). I need a solution for a Bash script on Linux.

I am able to submit a command using echo for a single line and then calculate the number of days from the current date by using cut on the 5th field (see below)...

echo "false|aaa|user|aaa001|2014-12-11" | echo $(( ($(date --date=date  "%Y-%m-%d"  %s) - $(date --date=cut -d'|' -f5  %s) )/(60*60*24) )) 
2590

I don't know how to do this one line at a time, capture the 'number of days' value and then append it to each line in the file.

CodePudding user response:

Here's an approach using

  • paste to append the outputs
  • sed to arrange the empty lines and
  • awk to calculate the desired days.

This works with GNU date. BSD date has to use something like date -jf x %s.

% paste -d"\0" file <(cut -d"|" -f5 file |
         sed 's/^$/#/' |
         xargs -Ix date -d x  %s 2>&1 |
         awk -v cur="$(date -d "1/13/2022"  %s)" '/invalid/{print 0; next} 
           {print int((cur-$1)/3600/24)}')
false|aaa|user|aaa001|2014-12-11|2590
false|bbb|user|bbb||0
false|ccc|user|ccc|2021-10-19|86
false|ddd|user|ddd|2018-11-16|1154
false|eee|user|eee|2020-06-02|590

Also date returns date: invalid date ‘#’ in the empty case. If any other implementation behaves differently the awk regex has to be adjusted accordingly.

  •  Tags:  
  • Related