0

This is similar to How to list folders using bash commands?. I have a folder structure of the format foo/YYYY/MM/DD/HHMM (at 10 minute intervals). What is the easiest way to get the previous and next folder's name?

I thought of

sTimeNow=$(date "${iYear}/${iMnt}/${iDay} ${iHr}:${iMin):00")
sTimeBefore=$(date "${sTimeNow} - "10 minutes")
sTimeAfter=$(date "${sTimeNow} + "10 minutes")

and with a bit (understament...) of formatting could get the two directories.
However the date maths probably not the best way to go about it, and I have missing dates (which is my ultimate aim to fix)

Also thought of populating a list

MyList='ls -dr *"
iFolder= get current folder index (how?)
sFolderBefore=$Mylist[${iFolder}-1]  so much easier
sFolderAfter=$Mylist[${iFolder}+1]

(all the above likely to have syntax errors, apologies novice)

Miles
  • 1

1 Answers1

0

I would try something like:

find {root_of_folders} -type d | sort | grep -A 1 "$(basename "$PWD")\$" | tail -1

In other words: lits all the dirs and find the one that comes after the current one in the list. With the ending \$ it iterates your subdirectories, without it it goes to the next directory at same level.

For the previous directory you use -B 1 and head -1.

Edit: some enhancements:

  1. the code above has problems if file names contain things that can be interpreted as regexp syntax (characters in brackets, in particular), so better make this a grep -F (but you can no longer use the \$)

  2. To avoid false hits if a directory name is a non-initial part of another one, prefix with a / to force the match to occur from the beginning.

So, the improved form is:

find {root_of_folders} -type d | sort | grep -A 1 -F "/$(basename "$PWD")" | tail -1
xenoid
  • 10,597