简体   繁体   中英

Use PowerShell to determine length of a line in a text file

I'm new to PowerShell, but I would like to use it, because there isn't a easy way to get the length of a string in Windows batch.

I need to write a piece of code in PowerShell that go through each line in a .txt file and determine the character length of that line. If the character length is over 250 then....etc.

The ....etc part is not important at the moment :)

In Windows batch I would write it like this:

FOR /F %%A IN ("C:\TestFile.txt") DO (
    SET LINE=%%A
    If LINE > 250 characters then (        ' This line is made up
    ....etc
    )

How can I do it?

The following will do what you want:

$data = Get-Content "C:\TestFile.txt"
foreach($line in $data)
{
   if ($line.Length -gt 250) {
       Write-Host "A match"
   }
}

Try this:

:: Not fully tested:
for /f "delims=" %%s in (C:\TestFile.txt) do (
   set "x=%%s" & set /A y+=1
   setlocal enabledelayedexpansion
   for /f "skip=1 delims=:" %%i in ('"(set x&echo()|findstr /o ".*""') do set/a n=%%i-4
   if !n! gtr 250 echo Line !y! Length !n!
   endlocal
)

Was looking for this today and found an elegant solution here: https://softwarerecs.stackexchange.com/questions/38934/finding-the-longest-line-of-a-document/38936

GC "c:\folder\file.txt" | Measure -Property length -Maximum | Select Maximum 
GC "c:\folder\file.txt" | Sort -Property length | Select -last 1

Important: credit goes to Pimp Juice IT from the link above, I'm just copy/pasting : )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM