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)
  • gratuitous zsh: cd $(zsh -c 'echo *(/on[-1])') – Jeff Schaller Jan 18 '18 at 19:30
  • If any of the answers solved your problem, please accept it by clicking the checkmark next to it. Thank you! – Jeff Schaller May 16 '18 at 10:50
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

| improve this answer | |
  • Thanks for quick turn around, however I got below exception. Find: paths must precede expression...... – Satya Jan 18 '18 at 19:45
  • 3
    The correct syntax is: cd $(find /home/cg/root/2018/01 -type d | sort -r | head -1) – Nasir Riley Jan 18 '18 at 19:48
0

This will do it

cd $(ls /home/cg/root/2018/01 | sort -n -r | awk 'NR==1 {print $1})
| improve this answer | |
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:

| improve this answer | |
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.

| improve this answer | |
0

You can do it in simple way.

cd /home/cg/root/2018/01; cd `ls -r | head -n 1`
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.