Shortest Windows batch file code to get first line

2019-03-15 04:11发布

I am looking for the shortest amount of code possible that will get the first line of a text file and set it to a variable in Windows.

There are lots of examples of this kind of thing in other threads on this StackExchange site but I am not looking for how to loop through and display all lines in a file. What I want is to just simply get the first line.

6条回答
Ridiculous、
2楼-- · 2019-03-15 04:34

this is just a slightly shorter version:

set/pz=<file
echo %z%
查看更多
Evening l夕情丶
3楼-- · 2019-03-15 04:40

If delayed expansion has been enabled before (Setlocal EnableDelayedExpansion) then there's a shorter (one-liner) version

set /pz=<filename.txt&echo !z!
查看更多
【Aperson】
4楼-- · 2019-03-15 04:44
set /p var= <Text.txt
echo %var%

Referenced from: http://forums.techguy.org/software-development/551867-batch-file-read-line-text.html Ironically the poster is able to get the first line but wanted to loop through the whole file!

查看更多
姐就是有狂的资本
5楼-- · 2019-03-15 04:49

I couldn't get this to work under Windows 7; the variable was simply not set. But here's a slightly longer solution:

for /F "delims=" %%i in (Text.txt) do (  
  set Z=%%i
  goto BREAK1
)
:BREAK1
echo %Z%
查看更多
SAY GOODBYE
6楼-- · 2019-03-15 04:49

I had to change the line of file for a text file inside Program Files(x86) directory. After trying a lot of solutions, the following solution worked for me:

Steps:

Step 1) use type command piped with findstrto get a file with the desired data

Step 2) delete the original file

Step 3) use type command to move the content back to the file with the original file name

Step 4) Delete the new file

Example:

@echo off
set originalFile="C:\Program Files (x86)\<Target File Path>\<Target File Name>"
set newFile="C:\Program Files (x86)\<Target File Path>\<Target newFile Name>"
if exist %originalFile% (
    type %originalFile% | findstr /v T4VSHost >> %newFile%
    del %originalFile% /F /Q
    type %newFile% >> %originalFile%
    del %newFile% /F /Q
)
@echo on

Note:

When I tried writing the change back to the original file in step 1, the result was a an empty file.

Note the string I am matching is T4VSHost, which occurs in the file at path

C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\Entity Framework Tools\Templates\Includes\EF6.Utility.CS.ttinclude

查看更多
三岁会撩人
7楼-- · 2019-03-15 04:59

just FYI...

I tried it and didn't work. But I realized finally that I had to reproduce the text file (originally the text file is generated by a powershell script) so when I did this and it works.

:: output to different file
Type Text.txt > text2.txt

Then apply the same code (change text.txt to text2.txt)

set /p var= <Text2.txt
echo %var%

If I use the original one, I would either get garbage in %var%, not sure if the text file has not <CR> or what. Anyway, by reproducing the text file, it seems working fine.

查看更多
登录 后发表回答