Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 删除从文件到行尾的子字符串_Regex_Powershell_Wildcard - Fatal编程技术网

Regex 删除从文件到行尾的子字符串

Regex 删除从文件到行尾的子字符串,regex,powershell,wildcard,Regex,Powershell,Wildcard,考虑文件dummy.txt,如下所示: SomeMessage: "BLABLABLA Value 'V1' of attribute 'CLR', Additional Information: 'Sometext'." SomeMessage: "BLABLABLA Value 'W2' of attribute 'HGT', Additional Information: 'Sometextmore'." SomeMessage: "BLABLABLA Value 'X3' of attr

考虑文件dummy.txt,如下所示:

SomeMessage: "BLABLABLA Value 'V1' of attribute 'CLR', Additional Information: 'Sometext'." SomeMessage: "BLABLABLA Value 'W2' of attribute 'HGT', Additional Information: 'Sometextmore'." SomeMessage: "BLABLABLA Value 'X3' of attribute 'SND', Additional Information: 'EvenSomeBiggerBulk'." 我试过:

(Get-Content dummy.txt).Replace(', Additional*." ', '') | Set-Content temp.txt 

但这使文件保持不变。

您几乎是正确的

(Get-Content dummy.txt) -replace ", Additional.*" | Set-Content temp.txt 
使用PowerShell操作符
-Replace
代替.NET字符串方法
.Replace()

NET方法接受两个字符串,
oldValue
newValue
,并且不使用正则表达式。它只能替换精确匹配

PowerShell运算符也接受两个字符串,但它使用正则表达式。如果您只想删除匹配项,
newValue
字符串是可选的。

我会选择:

(Get Content dummy.txt)-替换(“,\sAdditional.*”,“”)>temp.txt


我更喜欢
重定向器(管道也可以工作)。我改进了
regex
以匹配您正在搜索的内容。

*。
?你是说
*
?:)非常感谢。下面的解决方案效果很好:
(Get Content dummy.txt)-replace“,Additional.*”| Set Content temp.txt
但是,有人能解释一下为什么它是
*
而不是
*。
@SamNorton在regex
中是“任意字符”,而
*
意味着“将上一个字符重复零次或多次”,因此您的
附加的*
实际上是重复的字母
l
的任意数字,后跟任意一个字符,希望这能解释它。@ConnorLSW谢谢您的回答。@tukan
在正则表达式中不是一个特殊字符,没有必要逃避它
\s
并不比空格好,特别是因为OP的文件只有一个空格。你提到的正则表达式的改进在哪里?@Tomalak你说得对,-将修复它
\s
对于同样为真的空格是等效的。改进是视觉上的,而不是功能上的。如果您有复杂的regexp,那么查找
\s
比查找``更容易,但是当您进行非regex替换时,您必须在搜索字符串中使用规则空格,这样很容易查找。在正则表达式中不难发现。:)这是一个偏好的问题,真的。@Tomalak这是完全正确的。因为我做了一些复杂的regexp,所以我就有了这个习惯,它从来没有咬过我:),所以我称之为改进。好吧,很公平。
(Get-Content dummy.txt) -replace ", Additional.*" | Set-Content temp.txt