Title: How to replace all characters between two patterns in Bash?
Tags: bash;sed;echo;substitution;tr
Question: I'm looking to replace all chars of a line of variable length starting with ( and ending with ) by = symbols.
Example:
line1 with some words
( + + +  +    +  +  )
line3 with some words
should be changed to:
line1 with some words
=====================
line3 with some words
It tried the following bash code, but it doesn't work, as it also changes white spaces in line1 und line3, too:
echo -e &quot;line1 with some words\n( + + +  +    +  +  )\nline3 with some words&quot;|tr ' (+)' '='
Result:
line1=with=some=words
=====================
line3=with=some=words
What do I need to fix in order to make it work?
Comment: can you confirm a) you'll only have a single pair of parens on a line and b) the line always starts with `(` and ends with `)`? or is it possible the line could have other characters before the `(` and/or after the `)`? could the line have multiple sets of the pattern `(...)` and if the answer is 'yes' ... could they be nested (eg, `(...(...)...)`?

Comment: Yes, I can confirm the input is exactly as shown. There are no other lines. Only line 2 needs to be replaced. @Cyrus already posted the right answer.


Here is another answer: If a row starts with ( and ends with ) then replace in this row all characters with =.
echo -e &quot;line1 with some words\n( + + +  +    +  +  )\nline3 with some words&quot; |\
sed '/^(.*)$/ s/./=/g'

Here is another answer: Assumptions:
a set of parens may show up more than once in a line
parens are not nested
there may be other characters before the ( and/or after the )
Sample input:
$ cat input.txt
line1 with some words
( + + +  +    +  +  )
line3 with some words
xx (abc) yy (def) zz
One awk idea:
BEGIN { regex=&quot;[(][^)]*[)]&quot; }
{ while (match($0,regex)) {
x=&quot;&quot;
for (i=1;i<=RLENGTH;i++)
x=x &quot;=&quot;
gsub(regex,x)
}
}
1' input.txt
This generates:
line1 with some words
=====================
line3 with some words
xx ===== yy ===== zz

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 2, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2022:00:06/05/22', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<bash><sed><echo><substitution><tr>', 'Title': 'How to replace all characters between two patterns in Bash?', 'ViewCount': 64, 'id': 72510950, 'user_AboutMe': None, 'user_AccountId': 25480766.0, 'user_DisplayName': 'questioneer', 'user_Reputation': 1.0, 'user_Views': 2.0, 'user_id': 19277157.0}}