[英]powershell substring of substring
I'm trying to substring a substring of a text file in order to cut out the text I need from a text file. 我试图对文本文件的子字符串进行子字符串化,以便从文本文件中切出所需的文本。
In this example if the file contains the following 在此示例中,如果文件包含以下内容
this is a test example
这是一个测试示例
second line of text文字第二行
third line of text文字第三行
I want to remove everything before second, then get everything between "second" and "third line". 我想在第二秒之前删除所有内容,然后在“第二行”和“第三行”之间获取所有内容。 So the output would be
所以输出将是
second line of text
文字第二行
third line第三行
This is what I have and it works if put a hardcoded length in $second, but I can't get the length correct as a variable: 这就是我所拥有的,并且如果在$ second中放入一个硬编码的长度,它可以工作,但是我不能将长度作为变量正确:
$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
couple of ways you could do this: 您可以通过以下两种方法执行此操作:
first- specify what you dont want 首先-指定您不想要的
Get-Content -Path textfile |
Where-Object {$_ -NotLike 'this is a*'} |
Set-Content file2.txt
second- specify what you do want 第二-指定您想要的
Get-Content -Path textfile |
Where-Object {$_ -Like 'second*' -or $_ -like 'third*'} |
Set-Content file2.txt
or 要么
Get-Content -Path textfile |
Where-Object {$_ -match '^(second|third)'} |
Set-Content file2.txt
Here I was getting text data and then splitting it by single line ( `n ) doing so will make an array of string lines. 在这里,我获取文本数据,然后将其按单行( `n )拆分,这样将形成字符串行数组。 Then I get strings number by array enumeration [1..2].
然后我通过数组枚举[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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.