PDA

View Full Version : Simple'ish Linux question


cbergy
10-31-2006, 06:29 PM
Hey guys,

I'm attempting to setup a cronjob, and one of the things the script has to do is cd to a directory. Unfortunately, the directories name is dynamic. Basically, there's 5 dirs with timestamps, and I want the 5th dir. I'm attempting something like this:

ls -C | awk '{print $5}' | xargs cd

I've tried:

ls -C | awk '{print $5}' | cd xargs

as well.

I think it's close, since I can get it to print out the dir's name no problem. It's just my lack of knowledge with the xargs command.

Any ideas on what I'm missing?

(if this post doesn't make much sense, let me know and I'll re-write it.

Thanks in advance!

dkozinn
10-31-2006, 09:04 PM
Well, this is one way to get it to work:

cd `ls -C | awk '{print $5}' `

which basically says to cd to the output out of the command. (Notice the "backticks" around the command.)

xargs is usually used for a long string of arguments (there are other uses), so it's kinda overkill for this.

This isn't a foolproof way to do this though, since if you have less than 5 directories, or if a directory contains a space, etc. But if you're reasonably sure that neither of those will happen, I guess it's kinda ok.

If you're just looking to get the most recent (or oldest) files, there are other ways that you could do that, etc.

cbergy
11-01-2006, 01:28 PM
That's working wonders for me, thanks David!

Fortunately, I'm guaranteed that there will always be 5 directories, sorted by their timestamp. However, for curiosities sake say I wanted to always use the newest directory. Which command would I use to go about that?

Matt
11-01-2006, 01:31 PM
ls -t | awk '{print $1}'

will order by time and print the last modified directory. If you want to sort by the date of creation for a particular directory, switch "t" with "c" to sort by ctime instead.

dkozinn
11-01-2006, 02:07 PM
Glad that worked out OK for you Chuck.

As Matt noted, there are other ways to look at stuff, ls has quite a large number of options. "man ls" (at the shell prompt) is your friend. :idea:

One particularly useful option, when dealing with sorting files by time, is the "r" option to reverse the order of the sort. So instead of having the newest file first, if you wanted the oldest first you could just use "ls -tr" to reverse the order of the sort.

cbergy
11-02-2006, 12:43 PM
Great, thanks for the tips.

I guess I'll still have to stick to using cd with an awk wrapped in 'backticks'.

Fun stuff. :)

Matt
11-02-2006, 03:18 PM
Alternatively you can replace `` with $(), i.e. cd $(ls | awk '{print $1}').