Wednesday, April 13, 2022

[SOLVED] How to open the last folder irrespective of name on Bash

Issue

I’m currently working with a program that creates a folder with a time stamp and puts some files into it.

I want to write a script to automate retrieval of the file from last or second last folder by alphabetical order.

How do I do this on bash?

Image for reference. I want to retrieve a file from the 18-38 folder or the 17-45 folder.

enter image description here


Solution

I want to write a script to automate retrieval of the file from last or second last folder by alphabetical order.

cd path/to/02-March-2022

last_dir=$(printf '%s\n' */ | sort | tail -n 1)
second_last_dir=$(printf '%s\n' */ | sort -r | sed '2!d; 2q')
  • You can remove or add sort's -r to switch between Nth newest and Nth oldest.

Edit:

  • Globs are always sorted alphabetically (according to current locale), so the first sort is actually superfluous. But sort is useful if you need the extra sort flags, or to sort by specific fields, suffixes, etc.
  • Both sort and pathname expansion are affected by the current locale, so consider setting LC_ALL=C for consistent behavior. (export LC_ALL=C or LC_ALL=C sort for sort to see it).


Answered By - dan
Answer Checked By - Candace Johnson (WPSolving Volunteer)