如何使用findstr提取文件中的某些文本 [英] How to extract certain text inside a file using findstr

查看:26
本文介绍了如何使用findstr提取文件中的某些文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试扫描文本文件,但只想获取版本

I'm trying to scan a text file, and wanted to get the version only

我试过运行这个

>for /f "usebackq tokens=2 delims=, " %i  in (`findstr /l "version" "C:\Test\myfiles\package.text"`) do echo %i

但是它返回一个条目两次

however it's returning an entry twice

echo "4.2.20"
"4.2.20"

文本文件具有这种格式

 "version":  "4.2.20",

如何使用findstr只返回这种格式的确切版本4.2.20

how to use findstr to return only the exact version in this format 4.2.20

谢谢!

推荐答案

问:有没有办法返回以下格式的4.220(去掉最后一个小数点/句点?)

答:有.拆分版本字符串(像处理文件名一样处理它,因此第一部分 (%%~ni, "Filename") 在最后一个点之前获取任何内容,第二部分 (%%~xi, extension"得到最后一个点和后面的所有内容.然后简单地从extension"中删除点并合并两个子字符串:

A: there is. Split the version string (handle it like a filename, so the first part (%%~ni, "Filename") gets anything before the last dot and the second part (%%~xi, "extension" gets the last dot and everything after). Then simply remove the dot from the "extension" and merge the two substrings:

@echo off
setlocal 

for /f "usebackq tokens=2 delims=, " %%i  in (`findstr /l "version" "C:\Test\myfiles\package.text"`) do (
  set "major=%%~ni"
  set "minor=%%~xi"
)

set "version=%major%%minor:.=%"
echo method 1: %version%

set "version=%major%%minor:~1%"
echo method 2: %version%

可以在单个命令行中完成,但是当您需要延迟扩展时,这会变得丑陋,难以阅读和维护.不值得付出努力,除非您对此有特殊要求,恕我直言.所以(因为你还标记了 batch-file)我坚持了这一点.

It is possible to do it in a single command line, but as you need delayed expansion, this gets ugly, hard to read and maintain. Not worth the effort, except you have a special requirement for that, IMHO. So (because you also tagged batch-file) I stuck to that.

这篇关于如何使用findstr提取文件中的某些文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆