Home > Software design >  How to replace all characters between two patterns in Bash?
How to replace all characters between two patterns in Bash?

Time:06-06

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?

CodePudding user response:

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'

CodePudding user response:

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
  • Related