1748156 Members
3845 Online
108758 Solutions
New Discussion юеВ

Re: Help with awk.

 
Juan Antonio Llano
Occasional Advisor

Help with awk.

Hi,

When I do a "ls" in a given directory, I want to parse it so that it prints all the files except the last four:

[root@test sample]# ls -ltr
total 0
-rw-r--r-- 1 root root 0 feb 8 08:54 one
-rw-r--r-- 1 root root 0 feb 8 08:54 two
-rw-r--r-- 1 root root 0 feb 8 08:55 three
-rw-r--r-- 1 root root 0 feb 8 08:55 four
-rw-r--r-- 1 root root 0 feb 8 08:55 five
-rw-r--r-- 1 root root 0 feb 8 08:55 six

I want it to show all the files but the four most recents, I mean: one and two only.

How can I do this???
6 REPLIES 6
Jose Mosquera
Honored Contributor

Re: Help with awk.

Hi,

Please try this:
[root@test sample]# ls -ltr|tail -4

Rgds.
Jose Mosquera
Honored Contributor

Re: Help with awk.

Hi again,
Ooops, to show one and two files try:
[root@test sample]# ls -ltr|head -2

Rgds.
Hakki Aydin Ucar
Honored Contributor

Re: Help with awk.

As simple solution in case of you just 2 files, maybe it is better ;
# ls -lrt |tail -6|head -2
James R. Ferguson
Acclaimed Contributor

Re: Help with awk.

Hi:

> I want it to show all the files but the four most recents, I mean: one and two only.

So you mean only the first two files in the list. You could do this:

# ls -ltr | awk '!/^total/ && NR<=3'

...which skips the "total" or first line and then delivers lines two and three which are what you want.

Regards!

...JRF...
Dennis Handly
Acclaimed Contributor

Re: Help with awk.

>prints all the files except the last four:

Your query doesn't lend itself to any single command. That's assuming a directory with random number of files.

You could do:
ls -lt | tail +4
(Or possibly +5 to remove that total?)
The files will be in reverse order, two then one.

Otherwise you would have to put the output in a file and then count the lines before printing them. (Or you could do multiple ls(1) commands.)

Or you could have a complex awk script that buffers up the last 4 lines and if more, then print the first. And upon EOF, don't print those 4 lines.
Dennis Handly
Acclaimed Contributor

Re: Help with awk.

>ME: Or possibly +5 to remove that total?

You need +6 to skip total line and 4 more:
ls -lt | tail +$(( 4 + 2 ))