Remove files in a directory with ls grep and rm

greplsrm

I've a bash file on my project root with this line

$ ls | grep -P '^some_pattern_matching_regex_goeshere.txt$' | xargs rm -f

The above line removes all the .txt files from the project root but when I push all the .txt files to another folder e.g process_logs/ and try the same commands with ls, grep and rm its doesn't work.

This is what I tried but not worked to removed files on the process_logs directory.

 $ ls process_logs/ | grep -P '^some_pattern_matching_regex_goeshere.txt$' | xargs rm -f

N.B: I've also tried the command with simple regex pattern like
ls process_logs/ | grep -P '^*.txt$' | xargs rm -f to remove files from directory but It doesn't work though.

Best Answer

Try using find instead. If you don't want find to be recursive, you can use depth options:

find /process_logs -maxdepth 1 -mindepth 1 -type f -name 'some_shell_glob_pattern_here' -delete

Parsing the output of ls is not recommended because ls is not always accurate because ls prints a human-readable version of the filename, which may not match the actual filename. For more info see the parsing ls wiki article.

Related Question