From f681777d9e5c1d07baf03f49a4a7efc2d8e9b86f Mon Sep 17 00:00:00 2001 From: koalaman Date: Fri, 5 Jan 2018 13:18:31 -0800 Subject: [PATCH] Updated SC2010 (markdown) --- SC2010.md | 36 ++++++++++++++++++++++++++++-------- 1 file changed, 28 insertions(+), 8 deletions(-) diff --git a/SC2010.md b/SC2010.md index a6bf452..28c40c3 100644 --- a/SC2010.md +++ b/SC2010.md @@ -3,22 +3,42 @@ ### Problematic code: ```sh -ls /directory | grep target_file_pattern +ls /directory | grep mystring +``` + +or + +```sh +rm $(ls | grep -v '\.c$') ``` ### Correct code: ```sh -ls /directory/target_file_pattern +echo /directory/*mystring* ``` + +or + +```sh +# BASH +shopt -s extglob +rm -- !(*.c) + +# POSIX +for f in ./* +do + case $f of + *.c) true;; + *) rm "$f";; + esac +done +``` + ### Rationale: -Matching non-alphanumeric characters with grep may require escaping. Typically it is cleaner to use the built in pattern matching or another command like `find` +[Parsing ls](https://mywiki.wooledge.org/ParsingLs) 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: -Matching the negative list. - -```sh -ls /directory | grep -v NOT_target_file_pattern -``` \ No newline at end of file +None \ No newline at end of file