I am looking for the shortest amount of code possible that will get the first line of a t开发者_高级运维ext 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.
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!
This is just a slightly shorter version:
set/pz=<file
echo %z%
If delayed expansion has been enabled before (Setlocal EnableDelayedExpansion
or cmd started with /V:ON
option) then there's a shorter (one-liner) version
set /pz=<filename.txt&echo !z!
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%
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:
- Use
type
command piped withfindstr
to get a file with the desired data - Delete the original file
- Use
type
command to move the content back to the file with the original file name - 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
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.
精彩评论