b101101011011011
b101101011011011

Reputation: 4519

How order only folders by creation time using shellscript?

I have some folders and files inside a directory. I need to order only the folders by creation time.

How order all folders by creation time using shellscript? Thanks

Upvotes: 0

Views: 4575

Answers (4)

b101101011011011
b101101011011011

Reputation: 4519

Thanks for all the answers!

I got to solve my problem using the following command:

Order by Creation time: ls -clh | grep ^d | head -1 | rev | cut -d' ' -f1 | rev

Order by Modification time: ls -tlh | grep ^d | head -1 | rev | cut -d' ' -f1 | rev

Upvotes: 0

Shawn Chin
Shawn Chin

Reputation: 86864

You don't need a shell script. ls will order your files by creation time if you include the -ltc options.

From man ls:

-c     with -lt: sort by, and show, ctime (time of last modification of file 
                  status information) 
       with -l: show ctime and sort by name otherwise: sort by ctime

If you are only interested in directories and not regular files, you can filter the results by piping to grep

ls -ltc | grep ^d

Note: ^d means show only lines that start with the letter d which in the case of the output of ls -l means a directories.

update

From your answer, it looks like you're only interested in the filename of the newest file. Try this:

ls -ltc | awk '/^d/{print $NF; exit}'

Notes:

  • /^d/ : filter lines starting with 'd'
  • print $NF : print the last column
  • ; exit : exit immediately after the first match

Upvotes: 3

marco
marco

Reputation: 4675

I'd rather not use ls in scripts; use find instead:

find . -mindepth 1 -maxdepth 1 -type d -printf "%C@ %f\n" | 
    sort -n | 
    cut -d\  -f2-

The option "-mindepth 1" is there because we don't want "." in the output.

Alternatively, you can use stat too:

for dir in */; do
    stat -c "%Z $n" "$dir"
done | sort -n | cut -d\  -f2-

Upvotes: 0

qJake
qJake

Reputation: 17139

ls -d -t

Next time, RTM.

Upvotes: 0

Related Questions