I would like to be able to list all files within a folder which have a certain character as the third character. For each file, I then want to be able to perform an action, maybe delete or move. I've looked at the ls command, with grep/cut options, but I can't see how to get final list that I can then process.


  • Sorry, for clarification, it's only 1 level, not recursive. Thanks for the feedback. I will check which works and select the appropriate answer. – Keith Apr 11 '16 at 10:02

You can also use "find" command to find files and perform an action for each file individually.

find <directory_name> -name '??t*' -exec mv {} <target_directory> \;
  • This is better but searches recursively which (I think) is not what OP wants (though OP should clarify) and also lists directories. – don_crissti Apr 8 '16 at 17:21
  • add -mindepth 1 -maxdepth 1 to only find files in that one directory. – sborsky Apr 8 '16 at 17:27
  • xargs is another option here; ls ??t* | xargs -I {} mv {} <target_directory> – ASevkin Apr 8 '16 at 17:31
  • Better yet, mkdir -p targetdir && mv ??t* targetdir... – Stephen Kitt Apr 8 '16 at 18:00
  • ASevkin - why do you need the error prone ls | xargs when you can do it with find and do it right ? That is, if recursion is needed, otherwise you can simply glob - either way there's no point using ls. – don_crissti Apr 8 '16 at 18:02

You can do some pattern matching directly in the shell without invoking external programs.

Let's say you have a folder with the following files:

$ ls
ant  bat  bird  cat  cats  dog  fish

You could match only files 3 characters long ending in t like this:

$ ls ??t
ant  bat  cat

You could match any file with the 3rd character as t like this:

$ ls ??t*
ant  bat  cat  cats

See more documentation here: https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html

  • The problem here is the second part of the question: "For each file, I then want to be able to perform an action..." - and ls is not a good candidate for this job. – don_crissti Apr 8 '16 at 17:17
  • for f in ??t*; do stuff with $f; done ? – Jeff Schaller Apr 8 '16 at 18:06

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.