From 46b8904c6a0469ec0fa5f34b455ef92d8ea96c70 Mon Sep 17 00:00:00 2001 From: Cassidy Marble Date: Sun, 16 Jun 2024 00:03:03 -0400 Subject: [PATCH] Expand correct code section with examples for different kinds of sed expressions. --- SC2001.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/SC2001.md b/SC2001.md index 78442a0..4fb3485 100644 --- a/SC2001.md +++ b/SC2001.md @@ -12,6 +12,27 @@ string="stirng" ; echo "$string" | sed -e "s/ir/ri/" string="stirng" ; echo "${string//ir/ri}" ``` +*** + + +Here is a demonstration of the different search/replace available in Bash: + +```bash +var="foo foo" +# the following two echo's should be equivalent: +echo "$var" | sed 's/^foo/bar/g' +echo ${var/#foo/bar} +``` + +| $var | sed expression | bash equivalent | result | +|-----------|----------------|-----------------|-----------| +| foo foo | s/foo/bar/ | ${var/foo/bar} | bar foo | +| foo foo | s/foo/bar/g | ${var//foo/bar} | bar bar | +| foo foo | s/^foo/bar/ | ${var/#foo/bar} | bar foo | +| -foo foo | s/^foo/bar/ | ${var/#foo/bar} | -foo foo | +| -foo foo | s/foo$/bar/ | ${var/%foo/bar} | -foo bar | +| -foo foo- | s/foo$/bar/ | ${var/%foo/bar} | -foo foo- | + ### Rationale: Let's assume somewhere earlier in your code, you have put data into a variable (Ex: $string). Now you want to search and replace inside the contents of $string and echo the contents out. You could pass this to sed as done in the example above, but for simple substitutions, a parameter expansion can do it with less overhead. @@ -26,6 +47,7 @@ string="stirng" ; echo "$string" | sed -e "s/^.*\(.\)$/\1/" This is a bit simple for the example, and there are alternative ways of doing this in the shell, but this SC2001 flags on several of my crazy complex sed commands beyond this example's scope. Utilizing some of the more complex capabilities of sed is required occasionally, and it is safe to ignore SC2001. + ### Related resources: * Bash Manual: [Shell Parameter Expansion](https://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion)