DOS batch command to read some info from text file

后端 未结 5 926
醉话见心
醉话见心 2021-01-19 03:16

I am trying to read some info from a text file by using windows command line, and save it to a variable just like \"set info =1234\"

Below is the content of the txt

相关标签:
5条回答
  • 2021-01-19 03:47

    Use the for command to parse the file:

    for /f "skip=4 tokens=2" %%l in (svninfo.txt) do (
        set revision=%%l
        goto gotrev
    )
    
    :gotrev
    echo revision is %revision%
    
    0 讨论(0)
  • 2021-01-19 03:52

    Knowing how to use CMD scripting deftly is great, but using PowerShell is even better. Here's one way to do it:

    $revision = (( gc .\svninfo.txt | ? { $_.StartsWith( 'Revision: ' ) } ) -split ' ')[1]
    

    What's going on?

    $revision is a variable

    gc is Get-Content, aka type. Each line in the file becomes a string in a sequence (pipeline).

    ? is Where-Object. It filters the objects in a pipeline based on a condition.

    {} delimits a script block

    $_ is the current object in the pipeline.

    -split invokes String.Split() in .NET, giving you an array of objects

    [1] indexes in to the array

    0 讨论(0)
  • 2021-01-19 03:58

    Here's a one line version:

    for /f "tokens=2" %%i in ('findstr Revision: input.txt') do set revision=%%i
    
    1. findstr is used to filter the file. It will print "input.txt:Revision: 1234"
    2. Then the "tokens=2" means that we are interested in the second token, "1234". By default for breaks on white space.
    0 讨论(0)
  • 2021-01-19 03:58

    if you have can use GNU tools, such as gawk

    @echo off
    for /F %%a in ('gawk -F":" "$1~/Revision/{print $2}" file') do (
            set var=%%a
    )
    echo %var%
    
    0 讨论(0)
  • 2021-01-19 04:00

    The following code snippet shows how to do this:

    @echo off
    setlocal enableextensions enabledelayedexpansion
    set revision=
    for /f "delims=" %%a in (input.txt) do (
        set line=%%a
        if "x!line:~0,10!"=="xRevision: " (
            set revision=!line:~10!
        )
    )
    echo !revision!
    endlocal
    

    Its output is 1234 as desired.

    The setlocal is what I use in every script to ensure variables are treated in a known way. The for statement processes each line in the input file (the delims bit stops the line from being tokenised into separate words).

    The !line:~ bits are substrings with !line:~0,10! being the first ten characters and !line:~10! being the rest.

    So, basically, it checks every line to see if it starts with "Revision: " and, if so, extracts the rest of the line for later.

    0 讨论(0)
提交回复
热议问题