Help with awk. (49 Views)
Reply
Occasional Advisor
Juan Antonio Llano
Posts: 7
Registered: ‎10-02-2008
Message 1 of 7 (49 Views)

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???
Please use plain text.
Honored Contributor
Jose Mosquera
Posts: 1,013
Registered: ‎06-27-2002
Message 2 of 7 (49 Views)

Re: Help with awk.

Hi,

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

Rgds.
Please use plain text.
Honored Contributor
Jose Mosquera
Posts: 1,013
Registered: ‎06-27-2002
Message 3 of 7 (49 Views)

Re: Help with awk.

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

Rgds.
Please use plain text.
Honored Contributor
Hakki Aydin Ucar
Posts: 1,313
Registered: ‎08-16-2006
Message 4 of 7 (49 Views)

Re: Help with awk.

As simple solution in case of you just 2 files, maybe it is better ;
# ls -lrt |tail -6|head -2
Please use plain text.
Acclaimed Contributor
James R. Ferguson
Posts: 21,184
Registered: ‎07-06-2000
Message 5 of 7 (49 Views)

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...
Please use plain text.
Acclaimed Contributor
Dennis Handly
Posts: 24,753
Registered: ‎03-06-2006
Message 6 of 7 (49 Views)

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.
Please use plain text.
Acclaimed Contributor
Dennis Handly
Posts: 24,753
Registered: ‎03-06-2006
Message 7 of 7 (49 Views)

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 ))
Please use plain text.
The opinions expressed above are the personal opinions of the authors, not of HP. By using this site, you accept the Terms of Use and Rules of Participation