[Solved] Replace yesterday date with today's date except from the first line

Hello,

I have a file like this:

2012112920121130

12345620121130msABowwiqiq
34477420121129amABamauee
e7748420121130ehABeheheei

in case the content of the file has the date of yesterday within the lines containing pattern AB this should be replaced by the current date. But if I use "sed", it will replace all the occurrences and I want to leave the first line as it is.

How can I do that?

Any help is really appreciated.

#! /bin/bash
while read line
do
    if [[ $line =~ "AB" ]]
    then
        line=${line/$(date -d "-1 day" +%Y%m%d)/$(date +%Y%m%d)}
        echo $line
    else
        echo $line
    fi
done < file

OR

sed "/AB/ s/$(date -d "-1 day" +%Y%m%d)/$(date +%Y%m%d)/" file
1 Like

Awk Solution:-

#!/bin/bash

YESTR=$( date -d "-1 day" +%Y%m%d )
TODAY=$( date +%Y%m%d )

awk -v YS=$YESTR -v TD=$TODAY ' {
 if(NR==1) {
  print; next;
 }
 if(match($0,/AB/)>0) {
  gsub(YS,TD,$0); print;
 } else print;
} ' infile
1 Like

Thanks to both of you. It worked perfectly.