用powershell中的正则表达式替换文本文件的内容 [英] Replace the content of a textfile with a regex in powershell
问题描述
我有一个简单的文本文件,我需要一个 powershell 脚本来替换文件内容的某些部分.
I have a simple textfile and I need a powershell script to replace some parts of the file content.
我当前的脚本如下:
$content = Get-Content -path "Input.json"
$content -Replace '"(\d+),(\d{1,})"', '$1.$2' | Out-File "output.json"
是否可以像这样在没有内容变量的情况下将其写成一行?
Is it possible to write it in one line without the content variable, like this?
Get-Content -path "Input.json" | ??? -Replace '"(\d+),(\d{1,})"', '$1.$2' | Out-File "output.json"
我不知道如何在没有 $content 变量的情况下在第二个命令中使用第一个 get-content commandlet 的输出?是否有自动powershell变量
I don't know how I can use the output of the first get-content commandlet in the second command without the $content variable? Is there an automatic powershell variable
是否可以在管道中进行多于一个的替换.
Is it possible to do more replacements than one in a pipeline.
Get-Content -path "Input.json" | ??? -Replace '"(\d+),(\d{1,})"', '$1.$2' | ??? -Replace 'second regex', 'second replacement' | Out-File "output.json"
推荐答案
是的,您可以在一行中完成,甚至不需要管道,因为 -replace
可以像您一样处理数组希望它这样做(并且您可以链接运算符):
Yes, you can do that in one line and don't even need a pipeline, as -replace
works on arrays like you would expect it to do (and you can chain the operator):
(Get-Content Input.json) `
-replace '"(\d+),(\d{1,})"', '$1.$2' `
-replace 'second regex', 'second replacement' |
Out-File output.json
(为了可读性添加了换行符.)
(Line breaks added for readability.)
Get-Content
调用周围的括号是必要的,以防止 -replace
运算符被解释为 Get-Content
的参数.
The parentheses around the Get-Content
call are necessary to prevent the -replace
operator being interpreted as an argument to Get-Content
.
这篇关于用powershell中的正则表达式替换文本文件的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!