【问题标题】:Using sed to find/replace doesn't work on whole text file使用 sed 查找/替换不适用于整个文本文件
【发布时间】:2018-12-26 17:02:45
【问题描述】:

我正在尝试在 AppleScript 中使用 sed 来清理包含多行的文本文件。

源文件(test.txt)

Some random text

<html>
Lorem ipsum dolor sit amet rhoncus
</html>

Even more random text

苹果脚本

do shell script "sed 's/.*\\(<html.*html>\\).*/\\1/' test.txt"

期望的输出:

<html>
Lorem ipsum dolor sit amet rhoncus
</html>

收到的输出没有改变,因为 sed 只是逐行查看。有没有办法强制 sed 查看整个文件?

【问题讨论】:

  • 你知道&lt;html&gt;&lt;/html&gt; 总是一个人排队吗?

标签: macos sed applescript


【解决方案1】:

如果您对awk 满意,那么以下内容也可以帮助您。

awk '/<html>/,/<\/html>/' Input_file

【讨论】:

  • 这会产生 OP 中给出的正确所需输出,但是在 AppleScripts do shell script ... 命令中使用时,html&gt;/ 部分之前的正斜杠 / 需要双转义 \\。例如:do shell script "awk '/&lt;html&gt;/,/&lt;\\/html&gt;/' /Users/userName/path/to/test.txt"
【解决方案2】:

这可能对你有用(GNU sed):

sed -n '/^<html>/,/^<\/html>/p' file

使用 seds 类似 grep 的选项 -n 关闭自动打印,然后使用范围并仅打印范围内的行。

或者:

sed '/^<html>/,/<\/html>/!d' file

【讨论】:

  • 这些都产生了 OP 中给出的正确所需输出,但是在 AppleScripts do shell script ... 命令中使用时,html&gt;/ 部分之前的正斜杠 / 在两个示例中都需要双重转义 \\。例如:分别为do shell script "sed -n '/^&lt;html&gt;/,/^&lt;\\/html&gt;/p' /Users/userName/path/to/test.txt"do shell script "sed '/^&lt;html&gt;/,/&lt;\\/html&gt;/!d' /Users/userName/path/to/test.txt"
猜你喜欢
  • 2020-11-18
  • 2012-02-14
  • 2019-07-02
  • 2022-10-21
  • 1970-01-01
  • 2012-06-17
  • 2010-12-20
  • 2011-11-25
  • 1970-01-01
相关资源
最近更新 更多