Confusion about tail usage

Alexandra Zaharia f0rg3r at gmail.com
Mon Feb 18 15:35:56 UTC 2008


On Feb 18, 2008 5:15 PM, stan <stanb at panix.com> wrote:

> I am trying to write a quick shell script to delete all but the newest 3
> files in a directory. Getting a list sorted by time, I use ls -t. I
> figured
> I could use tail to print all the lines in it's input file, skipping the
> first 3 lines. I expected tail -n +3 would do this. But it does not.
>
> What am I doing wrong?
>
>
Hi Stan,

If I'm getting this right:

- You're trying to get a listing of the files in the current directory,
chronologically. You're interested though to get them one on each line,
that's why it would be better to use "ls -1t" instead of "ls -t". Notice how
the most recent files get "on top";

- You want to determine the newest 3 files of those: you'd need "ls -1t |
head -n 3" ("head" for "first");

- You want to delete all the other files except the "first" (as in: "most
recent") 3. OK... so first you gotta find out how many files you have there:

number_of_files=`ls -1t | wc -l`

Now you want to list all of them except for the first 3 (the most recent
ones). You'd need to do

ls -1t | tail -n $(($number_of_files-3))

(assuming you're using bash)

And finally if you really want to delete each of those files (whose names
are output by the command above), you'd need to run:

for x in `ls -1t | tail -n $(($number_of_files-3))` ; do
           rm -i "${x}" # rm -i for confirmation on each deletion
done


HTH,

Alex.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.ubuntu.com/archives/ubuntu-users/attachments/20080218/85bf5968/attachment.html>


More information about the ubuntu-users mailing list