سؤال

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.

هل كانت مفيدة؟

المحلول

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:-=%

نصائح أخرى

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top