In colors.txt, replace every run of two or more whitespace characters with one space.
Apply the replacement to all matches on each line.
red green blueWhich command is appropriate?
The ERE quantifier {2,} matches a run of at least two whitespace characters, and g applies the substitution to every match on a line.
Detailed explanation
sed 's/[[:space:]]{2,}/ /g' colors.txtIncorrect. Without -E, the quantifier is not interpreted as the intended ERE operator.
Incorrect. Without -E, the quantifier is not interpreted as the intended ERE operator.
sed -E 's/[[:space:]]{2,}/ /' colors.txtIncorrect. It replaces only the first match on each line.
Incorrect. It replaces only the first match on each line.
sed -E 's/[[:space:]]/ /g' colors.txtIncorrect. It matches one whitespace character at a time, so runs are not collapsed.
Incorrect. It matches one whitespace character at a time, so runs are not collapsed.
sed -E 's/[[:space:]]{2,}/ /g' colors.txtCorrect. -E enables {2,}, and g replaces every matching run.
Correct. -E enables {2,}, and g replaces every matching run.
Try it yourself
An example you can run in a temporary verification environment.
printf 'red green blue
' > colors.txt
sed -E 's/[[:space:]]{2,}/ /g' colors.txtExpected result
red green blueKey points
- Quantifiers in ERE
- The global substitution flag
- One match versus every match
Notes
- Environment: GNU sed 4.x
- Command output formatting can vary slightly by distribution or tool version.
- Run the example in a temporary directory or process when possible.
Foundation review
Read the scope first
Check whether the command acts on the current shell, a new process, an existing process, or a file.
Verify the observable result
Use the supplied command and compare the output with the expected result.