Creating page since it didn't exist when I came across the error.

cstackpole
2014-07-19 10:43:44 -07:00
parent 57297ddfdc
commit 26ae530c2f

20
SC2001.md Normal file

@@ -0,0 +1,20 @@
## SC2001: See if you can use ${variable//search/replace} instead.
### Problematic code:
string="stirng" ; echo "$string" | sed -e "s/ir/ri/"
### Correct code:
string="stirng" ; echo "${string//ir/ri}"
### Rationale:
Let's assume somewhere earlier in your code you have put data into a variable (Ex: $string). Now you want to do a search and replace inside the contents of $string. You could pass this to sed as done in the example above, but for simple substitutions utilizing the shell for the same feature is a lot simpler and should be utilized whenever possible.
### Contraindications
Occasionally a more complex sed substitution is required. For example, getting the last character of a string.
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 which are beyond the scope of this example. Utilizing some of the more complex capabilities of sed is required occasionally and it is safe to ignore SC2001.