Reputation: 11
I have a string that with brackets that enclose a single character, like such:
[a]
I want to take the character within the bracket and replace the bracket with the character, so the end result would look like:
aaa
This is what I came up with, but it doesn't work:
sed 's/\[ \([a-z]\) \]/\2/g' < testfile
Can someone please help me, and explain why my command isn't working?
Upvotes: 1
Views: 1833
Reputation: 2946
Try the following code:
$ echo "[a]" | sed 's/\[\([a-zA-Z]\)\]/\1\1\1/g'
or
$ echo "[a]" | sed -r 's/\[([a-zA-Z])\]/\1\1\1/g'
Output:
aaa
Upvotes: 1
Reputation: 4504
The issue with your patern sed 's/\[ \([a-z]\) \]/\2/g' < testfile
:
1) The pattern has only one group \([a-z]\), so \2 is invalid;
2) The pattern contains space, there is no match found;
3) To replace brackets, you need to capture them in a group.
My idea is, to catch all groups in a pattern, and replace them with \2\2\2
:
echo "[a]" | sed 's/\(\[\)\([a-z]\)\(\]\)/\2\2\2/g'
Or
echo "[a]" | sed 's/\(.\)\(.\)\(.\)/\2\2\2/g'
The output is:
aaa
Upvotes: 0
Reputation: 67567
I think you missed some basic concepts. First let's duplicate a single char
$ echo a | sed -r 's/(.)/\1\1/'
aa
parenthesis indicates the groups and \1
refers to the first group
Now, to match a char in square brackets and triple it.
$ echo [a]b | sed -r 's/\[(.)\]/\1\1\1/'
aaab
you need to escape square bracket chars since they have special meaning in regex. The key is you have to bracket in parenthesis the regex you're interested in and refer to them in the same order with \{number}
notation.
Upvotes: 0