powershell子串的子串

时间:2016-04-08 08:48:36

标签: powershell substring

我试图对文本文件的子字符串进行子字符串处理,以便从文本文件中删除我需要的文本。

在此示例中,如果文件包含以下内容

  

这是一个测试例子   第二行文字
  第三行文字

我希望在秒之前删除所有内容,然后在" second"之间取消所有内容。和#34;第三行"。所以输出将是

  

第二行文字
  第三行

这就是我所拥有的,如果将硬编码的长度放在$秒内,它可以工作,但我不能将长度作为变量得到正确的结果:

$text = ( Get-Content -raw Test.txt | Out-String ).Trim() 

$first = $text.IndexOf('second')

$second = $text.Substring($text.IndexOf('second'), ($text.length-1))

$third = $second.Substring(0, $second.IndexOf('third line'))

$text.Substring($first, $third) | Set-Content file2.txt

2 个答案:

答案 0 :(得分:1)

你可以通过以下两种方式实现这一目标:

首先 - 指明你不想要的东西

Get-Content -Path textfile | 
  Where-Object {$_ -NotLike 'this is a*'} | 
    Set-Content file2.txt

秒 - 指定你想要的东西

Get-Content -Path textfile | 
  Where-Object {$_ -Like 'second*' -or $_ -like 'third*'}  | 
    Set-Content file2.txt

Get-Content -Path textfile | 
  Where-Object {$_ -match '^(second|third)'}   | 
    Set-Content file2.txt

答案 1 :(得分:0)

在这里,我获取文本数据然后将其拆分为单行(`n )这样做将生成一个字符串行数组。然后我通过数组枚举[1..2]得到字符串数。

PS C:\> $string = @"
this is a test example
second line of text
third line of text
"@

$string.Split("`n")[1..2]
second line of text
third line of text
相关问题