简体   繁体   English

Powershell 搜索文本文件进行匹配并在行尾添加回车

[英]Powershell search text file for match and add carriage return at the end of the line

I am attempting to parse a text file and match set of characters and then add a carriage return at the end of that line to add some spacing.我试图解析一个文本文件并匹配一组字符,然后在该行的末尾添加一个回车符以添加一些间距。 I have tried a number of different ways to do this but haven't been successful.我尝试了许多不同的方法来做到这一点,但都没有成功。 Code sample below results in matching and returning only the lines with the match and doesn't add the carriage line.下面的代码示例导致匹配并仅返回匹配的行,而不添加回车行。

[string[]]$arrayFromFile = Get-Content -Path "C:\abc.txt" 
$Return = $arrayFromFile -match 'ghijk' -split "`r"
$Return | Out-File "C:\abc.txt" 

Results:结果:

  • ghij吉吉
  • ghmno格姆诺
  • ghabc加布

What I want to do is below.我想做的是下面。 Find the results "gh" and add a carriage return at the end of that line while keeping all of the content in the text file.找到结果“gh”并在该行的末尾添加回车符,同时将所有内容保留在文本文件中。

From:从:

  • abcdefmno abcdefmno
  • abcdefpqr abcdefpqr
  • ghij吉吉
  • abcdef abcdef
  • ghmno格姆诺
  • abcdef abcdef
  • abcdef abcdef
  • ghabc加布
  • mnop莫诺普

To:到:

  • abcdefmno abcdefmno
  • abcdefpqr abcdefpqr
  • ghij吉吉

  • abcdef abcdef
  • ghmno格姆诺

  • abcdef abcdef
  • abcdef abcdef
  • ghabc加布

  • mnop莫诺普

Thanks for any help!谢谢你的帮助!

You can achieve this in a single pipeline:您可以在单个管道中实现此目的:

Get-Content -Path "C:\abc.txt" | foreach {
   $_
   if ($_ -like "gh*") {
       "" # additional empty line
   }
} | Out-File "C:\abc.txt" 

Instead of inserting any line breaks or carriage returns, outputting an empty line (empty string) is enough.而不是插入任何换行符或回车,输出一个空行(空字符串)就足够了。 The line breaks will be automatically handled by Out-File .换行符将由Out-File自动处理。

Instead of -like "gh*" (to satisfy the requirement of your example), you can of course do -match <your regex> or whatever you like.而不是-like "gh*" (为了满足你的例子的要求),你当然可以-match <your regex>或任何你喜欢的。

We combine all the steps in a switch statement with the -Regex and -File parameters.我们结合与switch语句中的所有步骤-Regex-File参数。 It will read the file line by line, we match against letters gh and on those matching lines add a blank line to the output.它将逐行读取文件,我们匹配字母 gh 并在这些匹配的行上向输出添加一个空行。 All this is captured in $return and then we use Set-Content to write it back out.所有这些都在$return捕获,然后我们使用Set-Content将其写回。

$file = 'c:\abc.txt'

$return = switch -Regex -File $file {
    gh {$_; ''}
    default {$_}
}

$return | Set-Content $file -Encoding UTF8

Note Out-File can be problematic with encodings thus I changed it to Set-Content注意Out-File可能有编码问题,因此我将其更改为Set-Content

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

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