2

I have a file in which there is a line:

Password=md@2507

where 2507 is the date when I changed the password for the last time. I want a script that reads the date from the Password line of that file and then shows me the date after 10 days as this password will expire after 10 days of this date.

2

With GNU sed and GNU date:

sed -En 's#^Password=.*@([0-9]{2})([0-9]){2}$#date -d "\2/\1 +10 days" +%F#ep'

We turn the 2507 to 07/25 as GNU date expects dates in the US style. However note that 07/25 is understood as the 25th of July of the current year.

What that means is that if you run that command on 2017-01-02 on a Password=x@2712 input, you'll get a 2018-01-06 output (10 days after the 27th of December 2017).

What you could do instead is:

eval "$(date +'d=%d m=%m y=%Y')"
awk -v "y=$y" -v "today=-$m-$d" -F @ '
  /^Password=.*@[0-9]{4}$/ {
    d = "-" substr($NF, 3) "-" substr($NF, 1, 2)
    d = (d > today ? y - 1 : y) d
    system("date -d \"" d " +10 days\" +%F");
  }'

In eval "$(date +'d=%d m=%m y=%Y')", we get date to output the current date in d=25 m=07 y=2016 format. We take that and evaluate it as shell code so as to set the $d, $m and $y shell variables. It's better than doing d=$(date +%d) m=$(date +%m) y=$(date +%Y) as it runs only one date command and avoids the problem when that command is run at 23:59:59.9 on the last day of the month.

Then we run awk, with the y awk variable set to the content of the $y shell variable (2017) and today set to -01-02.

In awk, if the current record matches the ^Password=.*@[0-9]{4}$ regular expression. That is if it starts with Password= and ends in @ followed by 4 decimal digits, then we:

  • Extract the date in those last 4 digits and store it in the d variable as -mm-dd like for today.

  • If d is lexically greater than today, for instance in our example above -12-27 is greater than -01-02, then we set d to the year before (2016-12-27), and to the current year otherwise.

  • Then we run the date -d "2016-12-27 +10 days" +%F command. Assuming GNU date that means printing in %F format (that is YYYY-MM-DD) the date as specified by 2016-12-27 +10 days, that is 10 days after 2016-12-27.

  • You can avoid *GNU sed* if use date -f <(sed … – Costas Jul 25 '16 at 9:16
  • date can be simplyfied by 10 day instead +10 days – Costas Jul 25 '16 at 9:18
  • Thank u very much Mr. Stephane. Its very helpful for me. i m very new to Linux scripting. Can u please explain this whole command, i mean what each command does. – Pawan Mishra Jul 25 '16 at 11:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.