0

I have a folder which consists files numbered 1, 2, 3, 4, 5 and so on. These files are named as numbers only. Along with these files, I also have two folders in the same directory.

Am trying to extract the last five files from the directory (excluding folders and also files without numbers) whose file name is a number. So am trying to do something like this:

ls /var/lib/myFolder/prog/TEST_DEV/builds/ -t | head -n5

But this returns files along with my two directories.

Then i tried something like:

ls /var/lib/myFolder/prog/TEST_DEV/builds/ -p | tail -5

Which doesn't work as well.

Any suggestions on how to proceed?

user8478502
  • 23
  • 1
  • 7

1 Answers1

1

You may use shell globbing or a script that interprets Regular Expressions, like grep.

For example, in order to list all the files whose file names only contain numbers (one or more digits) you can go like this:

ls -1 | egrep '\b[0-9]+\b'

In order to retrieve the last 5 files, as you say, you need:

  1. to make sure you use a sorting rule of ls like ls -t for sort by last modified date
  2. to exclude the directories from the list you should exclude the filenames that include '/' at the end by using the regular expression \b[0-9]+\b that means the matches have 1 or more numeric digits from the beginning to the end. The '/' is available at the end of directory names because ls has the p option also.
  3. to limit the returned matches by using the tail -5 command

So, I guess something like this will work for you:

ls -1tp | egrep '\b[0-9]+\b' | tail -5

Reference to this SO question: Regular Expression usage with ls

Reference to a Grep cheat sheet.

sanastasiadis
  • 1,182
  • 1
  • 15
  • 23
  • Shell-globbing `!=` grep regexps. ;-) . For this Q, a useful example of shell globbing would be `ls -tp [0-9]` and then you can skip the first `egrep`. Good luck to all. – shellter Jun 28 '18 at 16:54
  • @shellter - your `ls -tp` will miss files with multiple digits, such as `123` – Stephen P Jun 28 '18 at 16:59
  • @StephenP ; Yes agreed. The O.P. specifically mentioned single digit filenames, so I've limited my comment to that need. It is easy to extend to `ls -tp [0-9] [0-9][0-9] ...` to catch as many digit-only filenames as can be expected. Everything is a trade off ;-). Good luck to all. – shellter Jun 28 '18 at 17:03