【问题标题】:Find a string and deleting from that string to the end of line batch script查找一个字符串并从该字符串删除到行尾批处理脚本
【发布时间】:2014-10-17 08:37:46
【问题描述】:

我需要一些关于批处理脚本的帮助。

在文件中查找一个字符串并删除该行的剩余部分。

例子:

This is my string before running the script.

查找字符串"before"并删除'直到行尾。

输出:

This is my string.

提前致谢。

【问题讨论】:

  • 根据你说的规则,结果不应该以句点结尾

标签: batch-file replace find


【解决方案1】:

sed 命令是你的朋友。

sed s/before.*//

这将只修改带有字符串“before”的行,并且对于这些行,删除字符串“before”及其后面的所有内容,直到行尾。如果您想就地编辑,请阅读有关如何使用-i 开关的手册页。

【讨论】:

  • 您好我正在寻找批处理脚本,看起来 sed 在 unix 中,我在 windows 中运行脚本。你能帮我用windows脚本吗?
【解决方案2】:

使用sed:

This is my string bere running the script This is my string before running the script This is my string befo running the script This is my string before running the script 使用单个正则表达式(匹配之前和之后的所有内容并替换为任何内容)

$ sed 's/before.*//' a This is my string bere running the script This is my string This is my string befo running the script This is my string

但也许你想要类似的东西

sed 's/\ *before.*/\./' a This is my string bere running the script This is my string. This is my string befo running the script This is my string.

这会删除单词之前的最终空格并添加一个点。

【讨论】:

  • 我正在寻找批处理/cmd 脚本,我正在 Windows 中运行该脚本。你能帮我用windows脚本吗?
【解决方案3】:

对字符串进行标记会有所帮助。这里的问题是,分隔符只是一个字符,而不是一个单词。因此,您必须先将其替换为 - 例如 - §:

set "string=This is my string before running the script."
for /f "delims=§" %%i in ("%string: before =§%") do echo %%i.

【讨论】:

    【解决方案4】:

    使用REPL.BAT - A hybrid JScript/Batch utility 非常简单,它在标准输入上执行正则表达式搜索和替换并将结果写入标准输出。它是一个纯脚本,可​​以在 XP 以后的任何现代 Windows 机器上运行。

    type file.txt | repl (before).* $1 >file.txt.new
    move /y file.txt.new file.txt
    

    【讨论】:

      猜你喜欢
      • 2011-03-14
      • 1970-01-01
      • 1970-01-01
      • 2021-02-24
      • 1970-01-01
      • 2022-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多