0

I want to go in the directory on the basis of highest directory number.

Path: /home/cg/root/2018/01. Inside this path I have multiple directories as below

15
16
17
So on..

In this case highest directory is 17 so I want to move in 17 directory... If a directory named 18 exists then want to go in 18.

Is there any way which can be done using the cd command?

Like :

cd /home/cg/root/2018/01/$(ls |tail -1)
ilkkachu
  • 138,973
Satya
  • 13

5 Answers5

1

You can use find sort and head to do this

cd $(find /home/cg/root/2018/01/* -type d | sort -r | head -1) should do the trick

0

This will do it

cd $(ls /home/cg/root/2018/01 | sort -n -r | awk 'NR==1 {print $1})
Nasir Riley
  • 11,422
0

Using a (temporary) bash array inside a function:

cdhighest() {
  local dirs=(/home/cg/root/2018/01/*)
  cd -- "${dirs[-1]}"
}

Then just run cdhighest and it will take you to the directory under /home/cg/root/2018/01 that sorts last.

Reference:

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
0

What you have pretty much looks like it should work, except that ls should of course be told to list the contents of the correct directory. But it wouldn't list the full paths and there's a bunch of other details. Plus the things listed in Why you shouldn't parse the output of ls(1)

Since the shell can list filenames, and it actually sorts them, we could use just printf with a glob:

$ cd "$(printf "%s\n" /home/cg/root/2018/01/*/ |tail -1)"

Of course, that requires the directory names don't contain newlines.

ilkkachu
  • 138,973
0

You can do it in simple way.

cd /home/cg/root/2018/01; cd `ls -r | head -n 1`
αғsнιη
  • 41,407
Prvt_Yadav
  • 5,882