Skip to content
Daniel Wright edited this page Feb 27, 2023 · 14 revisions

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 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.

Exceptions

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 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:

ShellCheck

Each individual ShellCheck warning has its own wiki page like SC1000. Use GitHub Wiki's "Pages" feature guerraart8 to find a specific , or see Checks.

Clone this wiki locally