Walker News

Uses Sed To Find Text And Add Single Quote Character

Question: How do I use GNU sed to enclose the matched pattern with a pair of single/double quote character?

Using & character

GNU sed command uses this ampersand character (&) to print the matched pattern.

In this example, the sed searches any word/string and insert single quote (‘) to surround it:
echo "111 open bal 777" | sed -e "s/[a-z][a-z]*/'&'/g"

111 'open' 'bal' 777

If you want to enclose the searched pattern with a pair of double quote, just switch them accordingly, i.e.:
echo "111 open bal 777" | sed -e 's/[a-z][a-z]*/"&"/g'

Using parentheses and escape character

GNU sed also uses the escaped parentheses to function as storage/register, i.e. \( and \), to store the found pattern.

The content of register can be retrieved by \1, where \1 is corresponding to the first parentheses, \2 is referring 2nd parentheses, etc.

In this example, the escaped curly brackets, i.e. { and }, is used together with the escaped parentheses, where the curly brackets is to tell sed exactly how many characters to register as found pattern:
echo "111 open bal 777"|sed -e "s/ \(.\{8\}\)/ '\1'/"

111 'open bal' 777

With reference to Bruce Barnett’s effort on these topics: introduction and tutorial of sed and regular expressions.

Custom Search

2017  •  Privacy Policy