IGG*_*GGt 8 powershell substring powershell-2.0
我有一个包含几千行文本的文件.我需要从中提取一些数据,但我需要的数据总是左边57个字符,最后37个字符.我需要的位(在中间)具有不同的长度.
例如 20141126_this_piece_of_text_needs_to_be_removed<b>this_needs_to_be_kept</b>this_also_needs_to_be_removed
到目前为止我有:
SELECT-STRING -path path_to_logfile.log -pattern "20141126.*<b>" |
FOREACH{$_.Line} |
FOREACH{
$_.substring(57)
}
Run Code Online (Sandbox Code Playgroud)
这摆脱了行开头的文本,但我看不出如何从最后删除文本.
我试过了:
$_.subString(0,-37)
$_.subString(-37)
Run Code Online (Sandbox Code Playgroud)
但这些都行不通
有没有办法摆脱最后的x个字符?
小智 28
要删除文本中的最后x个字符,请使用:
$text -replace ".{x}$"
Run Code Online (Sandbox Code Playgroud)
即
PS>$text= "this is a number 1234"
PS>$text -replace ".{5}$" #drop last 5 chars
this is a number
Run Code Online (Sandbox Code Playgroud)
如果我理解正确,你需要这个:
$_.substring(57,$_.length-57-37)
Run Code Online (Sandbox Code Playgroud)
虽然这似乎与你给出的例子没有关系,但是它会给你不同的中间部分,即从开始的57个字符开始到结尾的37个字符.
以下是从字符串中删除最后 37 个字符的方法:
\n\n$_.subString(0,$_.length-37)\nRun Code Online (Sandbox Code Playgroud)\n\n但 arco\xc2\xb4s 答案是解决您的整体问题的首选解决方案
\n