使用powershell替换文件指定行号处的文本 [英] Replacing a text at specified line number of a file using powershell

查看:84
本文介绍了使用powershell替换文件指定行号处的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有一个文件,例如 test.config ,该文件在第 140 行和第 170 行之间包含工作WARN",还有其他行中存在WARN"字样,但我想替换第 140 行之间的WARN"和 170 与单词DEBUG",并保持文件的其余文本相同,保存时WARN"仅在第 140 和 170 行之间被DEBUG"替换.其余所有文本不受影响.

IF there is one file for example test.config , this file contain work "WARN" between line 140 and 170 , there are other lines where "WARN" word is there , but I want to replace "WARN" between line 140 and 170 with word "DEBUG", and keep the remaining text of the file same and when saved the "WARN" is replaced by "DEBUG" between only lines 140 and 170 . remaining all text is unaffected.

推荐答案

看看 $_.ReadCount 会有所帮助.举个例子,我只替换第 10-15 行.

Look at $_.ReadCount which will help. Just as a example I replace only rows 10-15.

$content = Get-Content c:\test.txt
$content | 
  ForEach-Object { 
    if ($_.ReadCount -ge 10 -and $_.ReadCount -le 15) { 
      $_ -replace '\w+','replaced' 
    } else { 
      $_ 
    } 
  } | 
  Set-Content c:\test.txt

之后,文件将包含:

1
2
3
4
5
6
7
8
9
replaced
replaced
replaced
replaced
replaced
replaced
16
17
18
19
20

这篇关于使用powershell替换文件指定行号处的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆