批量 findstr 正则表达式从单行 grep 一个项目

发布于 2024-12-14 12:02:40 字数 617 浏览 7 评论 0原文

如何使用 Microsoft findstr 从一行中“grep”一个项目?

我有一行这样的内容:

<config>test</config><item>some data</item><date>2007-11-02</date><datestart>2007-10-31</datestart><path>d:\test\test\test.txt</path>

现在,如果我想 grep 中的内容,我该怎么写那个正则表达式?

需要注意的一件事是,我必须将 findstr 命令放入 for 循环中,以便 grep 日期并将其存储在变量中。

示例:

for /f "Tokens=* Delims=" %%i in ('findstr /r /c:"regex" file.txt') do (
    set date=%%i
    set date=!date:-=!
)

另外,我不想依赖令牌,因为它们可能会有所不同。

How can I use Microsoft findstr to "grep" an item from a single line?

I've got a line that goes something like this:

<config>test</config><item>some data</item><date>2007-11-02</date><datestart>2007-10-31</datestart><path>d:\test\test\test.txt</path>

Now if I want to grep the content inside of <date> and </date> how would I write that regular expression?

One thing to note is that I will have to take the findstr command into a for-loop in order to grep the date and store it in a variable.

example:

for /f "Tokens=* Delims=" %%i in ('findstr /r /c:"regex" file.txt') do (
    set date=%%i
    set date=!date:-=!
)

Also, I don't want to rely on tokens as they may vary.

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

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

发布评论

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

评论(2

假装爱人 2024-12-21 12:02:41

我们可以使用一个技巧来完成您想要的操作:读取变量中的行后,将 更改为分隔符,即不在行中(例如,$);然后,只需使用 for /F "tokens=2 delims=$" 即可获取其中的内容。

set /P the_line=< file.txt
set the_line=!the_line:^<date^>=$!
set the_line=!the_line:^</date^>=$!
for /F "tokens=2 delims=$" %%i in ("!the_line!") do set date=%%i
set date=%date:-=%

We may use a trick to do what you want: after read the line in a variable, change <date> and </date> by a delimiter character that is not in the line (for example, $); then, just use a for /F "tokens=2 delims=$" to get the contents inside.

set /P the_line=< file.txt
set the_line=!the_line:^<date^>=$!
set the_line=!the_line:^</date^>=$!
for /F "tokens=2 delims=$" %%i in ("!the_line!") do set date=%%i
set date=%date:-=%
暖树树初阳… 2024-12-21 12:02:41

您可以使用正则表达式 "[0-9][0-9][0-9][0-9]\-[0-9][0-9]\-[0-9][0 -9]" 这应该与您的日期匹配。

You could use the regex "[0-9][0-9][0-9][0-9]\-[0-9][0-9]\-[0-9][0-9]" which should match your date.

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