Mohit Arora Mohit Arora - 6 months ago 27
Bash Question

How to cd into the first directory after sorting

I have a folder in which there are directories

ABC_1
ABC_2
ABC_3
ABC_4
ABC_5
Test
XYZ


I want to sort them by date,remove the directories which do not contain ABC in their name and cd into the first directory.

I tried

cd $(/bin/ls -t1 | head -n 1)


This is not working.
Any help would be much appreciated

Thanks.

Answer

This will list only directories and filter out any folder that does not start with ABC_:

cd "$(ls -t1 -d */ |grep  "^ABC_" |head -n1)"

UPDATE:

You actually do not need grep

cd "$(ls -t1 -d ABC_*/ | head -n1)"
Comments