0

I have one scenario which I should need to implement in the Unix. In a directory, I would like to delete the files based on the appended date at the end of the file, these files are XML back files. The files should be deleted based on the below criteria. Keep only 3 lasted date files(Appended date in the files) in the set of files and delete remaining files.

Directory Files:-

Set 1:

Wf_ABC_201801011224.xml
wf_ABC_201801011220.xml
Wf_ABC_201801011241.xml
wf_ABC_201801011230.xml
Wf_ABC_201801011244.xml
wf_ABC_201801011260.xml

Set 2:

Wf_DCB_201501021224.xml
wf_DCB_201601031220.xml
Wf_DCB_201601041241.xml
wf_DCB_201401051230.xml
Wf_DCB_201701061244.xml
wf_DCB_201801061260.xml

Set 3:

Wf_XYZ_201501011224.xml
wf_XYZ_201601011220.xml
Wf_XYZ_201701011241.xml
wf_XYZ_201801011230.xml
Wf_XYZ_201801021244.xml
wf_XYZ_201801031260.xml
Wf_XYZ_201501041224.xml
wf_XYZ_201601051220.xml
Wf_XYZ_201601061241.xml
wf_XYZ_201401071230.xml
Wf_XYZ_201701081244.xml
wf_XYZ_201801091260.xml
  • is the date formate is %Y%m%d%H%M ? – msp9011 Aug 15 '18 at 18:26
  • Yes it is date format – surajreddy2 Aug 15 '18 at 18:27
  • cant we use the last modified date of these files? – msp9011 Aug 15 '18 at 18:28
  • These are set of files, every day we will push the new XML files in the directory, so the old files should be deleted based on above-mentioned criteria. – surajreddy2 Aug 15 '18 at 18:31
0

Try this,

D1=`date -d "1 day ago" +"%Y%m%d"` && D2=`date -d "2 day ago" +"%Y%m%d"` && D=`date   +"%Y%m%d"` && find . -type f -name "wf_*_*.xml" -not -name "wf_*_$D*.xml" -not -name "wf_*_$D1*.xml" -not -name "wf_*_$D2*.xml" -exec rm {} +
  • store the past 3 dates in D1,D2 and D
  • find the files with pattern wf_*_*.xml
  • then ignore the patters with past 3 dates as wf_*_$D*.xml,wf_*_$D1*.xml and wf_*_$D2*.xml
  • then remove the files
0

Try this:

for set in ABC DCB XYZ; do 
    printf "%s\n" [Ww]f_${set}_*.xml | sort -t_ -k3,3n | head -n -3 | xargs echo rm
done

If it looks like it has found the right files, rerun it without the echo

  • @surajeddy2, put your requirements in your question where everyone will read them. You need to crystal clear about what is a "set". – glenn jackman Aug 15 '18 at 20:28

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.