创建一个代码,使用条件语句读取文件内容直到内容中的特定字符串
Create a code that reads the content of file till particular string in the content using conditional statements
我有这个代码片段,它读取文件内容直到特定字符串,然后将文本文件内容复制到另一个文件
我尝试使用数组、拆分方法反转内容,但没有得到所需的输出。
$x = Get-Content -Path "C:\Users\Desktop\abc*.txt"
[array]::Reverse($x)
$d = foreach($line in $x)
{
if($line - like "HEllo")
{
#Read the text file till "hello" and copy the contents
}
}
您不需要使用内容反转数组或使用循环。
这是一个简单的解决方案:
$x = Get-Content -Path "C:\Users\Desktop\abc*.txt" -Raw;
$pos = $x.IndexOf("Hello"); #position of the substring
$result = $x.Substring(0, $pos); #cuting the left part (before the substring)
$result | Out-File "C:\Users\Desktop\abc_out.txt"; #Output the result to file
解释:
将文件内容获取为 原始 字符串。
求子串的位置"Hello"
把子串前面的部分剪掉
将结果输出到文件
我有这个代码片段,它读取文件内容直到特定字符串,然后将文本文件内容复制到另一个文件
我尝试使用数组、拆分方法反转内容,但没有得到所需的输出。
$x = Get-Content -Path "C:\Users\Desktop\abc*.txt"
[array]::Reverse($x)
$d = foreach($line in $x)
{
if($line - like "HEllo")
{
#Read the text file till "hello" and copy the contents
}
}
您不需要使用内容反转数组或使用循环。
这是一个简单的解决方案:
$x = Get-Content -Path "C:\Users\Desktop\abc*.txt" -Raw;
$pos = $x.IndexOf("Hello"); #position of the substring
$result = $x.Substring(0, $pos); #cuting the left part (before the substring)
$result | Out-File "C:\Users\Desktop\abc_out.txt"; #Output the result to file
解释:
将文件内容获取为 原始 字符串。
求子串的位置"Hello"
把子串前面的部分剪掉
将结果输出到文件