使用 GNU ed 将字符串替换为文本

发布于 2024-12-13 04:38:11 字数 269 浏览 6 评论 0原文

我想用包含每个可能字符的字符串替换 %foo% (在文件测试中找到)。由于缺少字符限制,以下操作是不可能的(在 BASHv4 中执行):

echo %foo% > test
replacement="//this//is//a//test"
ed -s test <<< "g/%foo%/s/%foo%/$replacement"

知道如何用每个可能的文本替换 %foo% 吗?

I want to replace %foo% (found in file test) with a string containing every possible character. Because of the missing character limitation, the following is not possible (executed in BASHv4):

echo %foo% > test
replacement="//this//is//a//test"
ed -s test <<< "g/%foo%/s/%foo%/$replacement"

Any idea how to replace %foo% with every possible text?

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

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

发布评论

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

评论(2

仅此而已 2024-12-20 04:38:11

我保证您可以通过在每个前面加上反斜杠来转义斜杠和反斜杠,从而非常接近您的目标。据我所知,这不能在 bash 中一步完成,所以你可以编写一个函数使其可读,或者享受你的倾斜牙签森林之旅:

$ echo %foo% > test
$ replacement="//this//is//a\\\\//test"
$ echo $replacement
//this//is//a\\//test
$ stage1=${replacement//\\/\\\\}
$ echo $stage1
//this//is//a\\\\//test
$ stage2=${stage1//\//\\\/}
$ echo $stage2
\/\/this\/\/is\/\/a\\\\\/\/test
$ ed -s test <<< g/.*foo.*/s/foo/$stage2/p
%//this//is//a\\//test%

换行符仍然是一个问题,但你不想保留无论如何,它们都在 bash 环境变量中,因为那里的空格不是很稳定。

I'll warrant the guess that you will get pretty close to your goal by escaping slashes and backslashes with a prepended backslash each. AFAIK that can't be done in bash in a single step, so you can either write a function to make it readable, or enjoy your trip to the leaning toothpick forest:

$ echo %foo% > test
$ replacement="//this//is//a\\\\//test"
$ echo $replacement
//this//is//a\\//test
$ stage1=${replacement//\\/\\\\}
$ echo $stage1
//this//is//a\\\\//test
$ stage2=${stage1//\//\\\/}
$ echo $stage2
\/\/this\/\/is\/\/a\\\\\/\/test
$ ed -s test <<< g/.*foo.*/s/foo/$stage2/p
%//this//is//a\\//test%

Newlines remain a problem, but then you don't want to keep them in bash environment variables anyway since whitespace isnt' very stable there.

む无字情书 2024-12-20 04:38:11

使用命令 r 可以从另一个文件加载文本,因此以下是一个有效的解决方案:

  • 将替换存储到另一个文件
  • 用 ed 打开文件
  • 将指针移动到位置
  • 删除行(后面是假替换)
  • 加载文本从带有 r FILE 的文件中
  • 写入并退出

With command r it is possible to load text from another file, so the following is a valid solution:

  • store replacement to another file
  • open file with ed
  • move pointer to location
  • delete line (fake replace follows)
  • load text from file with r FILE
  • write and quit
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文