Vishal Balaji
Vishal Balaji

Reputation: 697

How to open the last folder irrespective of name on Bash

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

Upvotes: 0

Views: 244

Answers (4)

dan
dan

Reputation: 5241

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).

Upvotes: 2

user1934428
user1934428

Reputation: 22247

Since globbing is, by default, alphabetically, I would load all the filenames into an array and pick the last element:

all_files=( * )
last_file=${all_files[-1]}

Two thinks are worth noting:

  1. If the directory entries may be files or subdirectories, you will have to loop over all_files in reverse order and pick the first one which is a plain file.
  2. You want to have them sorted alphabetically, but the meaning of this term, i.e. the sort order, depends on your environment - particular on the variable LC_COLLATE, respectively LC_ALL. You may want to set

i.e.:

export LC_ALL=C

before creating the array.

Upvotes: 0

pjh
pjh

Reputation: 8134

Try

folders=( path/to/02-March-2022/*/ )
last_dir=${folders[-1]%/}
second_last_dir=${folders[-2]%/}

Upvotes: 2

dawg
dawg

Reputation: 103884

Suppose you have these directories:

% ls -l
total 0
drwxr-xr-x  2 andrew  wheel  64 Mar  3 15:19 1
drwxr-xr-x  2 andrew  wheel  64 Mar  3 15:19 2
drwxr-xr-x  2 andrew  wheel  64 Mar  3 15:19 3
drwxr-xr-x  2 andrew  wheel  64 Mar  3 15:19 4
drwxr-xr-x  2 andrew  wheel  64 Mar  3 15:19 5

With the 'last' being 5.

You can do:

% for fn in *; do [[ -d "$fn" ]] && lf="$fn"; done
% echo "$lf"                                      
5

I cannot overstress, however, that the * may or may not give you what YOU think is the 'last directory.'

If you want to assure that it is the last one, sort them by stat and then take the last one.

Upvotes: 1

Related Questions