Skip to content
shellhacks.dev
Performance

Replace sed Calls with Parameter Expansion in Bash Loops

Replace $(echo "$f" | sed 's/a/b/') with ${f/a/b} inside a loop. The expansion runs in the shell, while the pipeline starts two processes for each value.

1 min read
Summarize in AI

A loop edits a value with sed for each of thousands of items, and most of its time goes to starting processes.

Shell
f=release-candidate-3
TIMEFORMAT='%R s'
time { for i in $(seq 1 1000); do r=$(echo "$f" | sed 's/candidate/final/'); done; }
time { for i in $(seq 1 1000); do r=${f/candidate/final}; done; }
echo "$r"
Text
0.972 s
0.003 s
release-final-3

The pipeline forks a subshell, then echo and sed as two processes, and sed starts, compiles its script and reads one line before it exits. The pattern substitution ${f/candidate/final} does the same replacement inside the running shell. Both are measured over 1000 iterations in a container, and the second finishes in a small fraction of the time. The syntax is described in Shell Parameter Expansion.

The expansion uses glob patterns and has no regular expressions, no case-insensitive flag and no back-references, so anything that needs those stays with sed. When the input is a file of many lines, one sed over the whole file is faster than any loop in the shell. Measure before rewriting a script, because the effect only matters when the loop runs thousands of times.

Share

More snippets

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.