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

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
  • 9,782
  • 4
  • 20
  • 31
  • Nice, I replaced {root_of_folders) with .. and it works perfectly. Not sure I follow the \$ it gives me the same answer with and without it – Miles Jul 20 '17 at 09:37
  • Also it only works for that day. e.g. from foo/2017/03/02/0000 it says the previous is foo/2017/03/02/0000. Works perfectly if it's the same day. – Miles Jul 20 '17 at 09:53
  • There is a difference if there are subdirectories. But since you are using `..` you must have only one level. – xenoid Jul 20 '17 at 10:55
  • That's because you are using `..` and not `/path/to/foo`. – xenoid Jul 20 '17 at 11:04