SC2010
Joachim Ansorg edited this page Nov 12, 2021
·
15 revisions
Don't use ls | grep. Use a glob or a for loop with a condition to allow non-alphanumeric filenames.
Problematic code:
ls /directory | grep mystringor
rm $(ls | grep -v '\.c$')Correct code:
ls /directory/*mystring*or
# BASH
shopt -s extglob
rm -- !(*.c)
# POSIX
for f in ./*
do
case $f in
*.c) true;;
*) rm "$f";;
esac
doneRationale:
Parsing ls is generally a bad idea because the output is fragile and human readable. To better handle non-alphanumeric filenames, use a glob. If you need more advanced matching than a glob can provide, use a for loop.
Exceptions:
-
lshas sorting options that are tricky to get right with other commands. If a specific order of files is needed, ls <sort options> | grep might be the best alternative. - network shares like AFS behave much faster using ls