questioneer
questioneer

Reputation: 1

How to replace all characters between two patterns in Bash?

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 "line1 with some words\n( + + +  +    +  +  )\nline3 with some words"|tr ' (+)' '='

Result:

line1=with=some=words
=====================
line3=with=some=words

What do I need to fix in order to make it work?

Upvotes: 0

Views: 466

Answers (2)

markp-fuso
markp-fuso

Reputation: 35006

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:

awk '
BEGIN { regex="[(][^)]*[)]" }
      { while (match($0,regex)) {
              x=""
              for (i=1;i<=RLENGTH;i++)
                  x=x "="
              gsub(regex,x)
        }
      }
1' input.txt

This generates:

line1 with some words
=====================
line3 with some words
 xx ===== yy ===== zz

Upvotes: 0

Cyrus
Cyrus

Reputation: 88776

If a row starts with ( and ends with ) then replace in this row all characters with =.

echo -e "line1 with some words\n( + + +  +    +  +  )\nline3 with some words" |\
sed '/^(.*)$/ s/./=/g'

Upvotes: 1

Related Questions