如何在bash中的两个模式之间替换所有字符?

发布于 2025-02-04 11:00:29 字数 540 浏览 4 评论 0原文

我希望替换以(并以)为单位=符号开始的可变长度线的所有字符。

示例:

line1 with some words
( + + +  +    +  +  )
line3 with some words

应该更改为:

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

它尝试了以下bash代码,但它不起作用,因为它也更改了Line1和Line3中的白色空间:

echo -e "line1 with some words\n( + + +  +    +  +  )\nline3 with some words"|tr ' (+)' '='

结果:

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

我需要修复什么才能使其正常工作?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

橘虞初梦 2025-02-11 11:00:29

如果一行以开头(,并以>)结束,则在此行中替换为=的所有字符。

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

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'
花心好男孩 2025-02-11 11:00:29

假设:

  • 一组Parens可能会在行中出现不止一次的帕伦斯(Parens)嵌套,
  • >(和/或之后)可能还有其他字符())

示例输入:

$ cat input.txt
line1 with some words
( + + +  +    +  +  )
line3 with some words
 xx (abc) yy (def) zz

一个awk构想:

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

这生成:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文