Home > Back-end >  Bash command: head
Bash command: head

Time:12-21

I am trying to find all files with dummy* in the folder named dummy. Then I need to sort them according to time of creation and get the 1st 10 files. The command I am trying is:

find -L /home/myname/dummy/dummy* -maxdepth 0 -type f -printf '%T@ %p\n' | sort -n | cut -d' ' -f 2- | head -n 10 -exec readlink -f {} \;

But this doesn't seem to work with the following error:

head: invalid option -- 'e'
Try 'head --help' for more information.

How do I make the bash to not read -exec as part of head command?

UPDATE1:

Tried the following:

find -L /home/nutanix/dummy/dummy* -maxdepth 0 -type f -exec readlink -f {} \; -printf '%T@ %p\n' | sort -n | cut -d' ' -f 2- | head -n 10

But this is not according to timestamp sort because both find and printf are printing the files and sort is sorting them all together.

Files in dummy are as follows: dummy1, dummy2, dummy3 etc. This is the order in which they are created.

CodePudding user response:

How do I make the bash to not read -exec as part of head command?

The -exec and subsequent arguments appear intended to be directed to find. The find command stops at the first |, so you would need to move those arguments ahead of that:

find -L /home/myname/dummy/dummy* -maxdepth 0 -type f -printf '%T@ %p\n' -exec readlink -f {} \; | sort -n | cut -d' ' -f 2- | head -n 10

However, it doesn't make much sense to both -printf file details and -exec readlink the results. Possibly you wanted to run readlink on each filename that makes it past head, in which case you might want to look into the xargs command, which serves exactly the purpose of converting data read from the standard input into arguments to a command. For example:

find -L /home/myname/dummy/dummy* -maxdepth 0 -type f -printf '%T@ %p\n' |
  sort -n |
  cut -d' ' -f 2- |
  head -n 10 |
  xargs -rd '\n' readlink -f

CodePudding user response:

I think you are over-complicating things here. Using just ls and head should get you the results you want:

ls -lt /home/myname/dummy/dummy* | head -10

To sort by ctime specifically, use the -c flag for ls:

ls -ltc /home/myname/dummy/dummy* | head -10

  • Related