简体   繁体   English

使用PowerShell确定文本文件中的行长

[英]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. 我是PowerShell的新手,但我想使用它,因为在Windows批处理中没有一种简单的方法来获取字符串的长度。

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. 我需要在PowerShell中编写一段代码,以遍历.txt文件中的每一行并确定该行的字符长度。 If the character length is over 250 then....etc. 如果字符长度超过250,则...等。

The ....etc part is not important at the moment :) .... etc部分目前并不重要:)

In Windows batch I would write it like this: 在Windows批处理中,我会这样写:

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 今天正在寻找它,并在这里找到了一个优雅的解决方案: 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 : ) 重要提示:信誉来自上述链接,位于Pimp Juice IT上,我只是在复制/粘贴:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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