I have write a command in the shell of linux to count the file (in total 8) starting with 'c'in the directory /bin

find /bin/[c]* -type f | wc -l 

What I wish to do now, it's save the name of the first 7 files in a text file, but I can not find the right command to join to my pipe.

  • 1
    Note that find is usually called like this find [starting-point] ... -name {names_to_searchs_for} .... What your command does, it expands the /bin/[c]* to a list of all files and directories starting with c in your /bin and then uses these files as starting-points for find. This way, it will also list all regular files in possible directories like /bin/commands1/. Instead you should use find /bin -name 'c*' -type f (Note the single quotes around the search term c*). Also, you don't need the brackets [...]. – Stefan Hamcke Dec 30 '18 at 20:44
find /bin/[c]* -type f | head -n 7 > textfile 
  • @Alexander Thanks. The only task to put accepted is that I need to save this infos in a text file – Gianni Spear Dec 30 '18 at 20:44
  • 1
    @GianniSpear. Just add > filename at the end of line. – Alexander Dec 30 '18 at 20:46

If you mean the first 7 in alphabetical order, with zsh:

printf '%s\n' /bin/c*(.[1,7]) > list.txt

If you mean

  • the 7 oldest ones, add the Om glob qualifier (c*(.Om[1,7]))
  • the 7 newest ones, add the om glob qualifier instead
  • the 7 smallest: oL
  • 7 biggest: OL

Note that in find /bin/[c]*, it's the shell that expands that glob and passes the resulting files (alphabetically sorted) as separate arguments to find.

Beware that if any of those files are directories, find will start to descend into them and list their content (in an unspecified order)

You'd want:

find /bin/c* -prune -type f | head -n 7 > file.txt

Where -prune is to prevent find from descending into any directory. But beware that using head that way only works if the file names don't contain newline characters (most likely the case in /bin but not guaranteed in the general case).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.