How to replace paired square brackets with other syntax with sed?
bash, sed
Solution
sed -e 's/\[\([^]]*\)\]/\\macro{\1}/g' file.txt
This looks for an opening bracket, any number of explicitly non-closing brackets, then a closing bracket. The group is captured by the parens and inserted into the replacement expression.
Problem
I want to replace all pairs of square brackets in a file, e.g., `[some text]`, with `\macro{some text}`, e.g.: ``` This is some [text]. This [line] has [some more] text. ``` This becomes: ``` This is some \macro{text}. This \macro{line} has \macro{some more} text. ``` - The pairs only occur on individual lines, never across multiple lines. - Sometimes there might be more than one pair on a single line, but they are never nested. - If a bracket is found alone on a line, without a pair, then it should not be changed. How can I replace these pairs of brackets with this code?