【问题标题】:Find and replace a word in all the files, which is falling under a searching criteria at Unix在所有文件中查找并替换一个单词,该单词属于 Unix 的搜索条件
【发布时间】:2018-09-20 13:12:04
【问题描述】:

我想替换所有子目录内所有文件中的一个单词,满足一些条件。

下面是详细的情况。

我必须替换所有不区分大小写的单词,例如 {classy, CLASSY, cLassy ,..} 到“Vintage”这个词。我也只需要 将其替换为不区分大小写的单词“insert”或“INSERT”。

所以如果我有 2 个文件具有以下内容。

File1.txt
asd asdsd INSERT asdasd classy
asddsdff sdf sdff sdf  CLASSY
sfre asfert asdd asd insert asdgweg 
qwe asfer wrererw  werer wewer INSERT CLassy


File2.txt
fhfgh asdsd insert asdasd ClASSY
asddsdff dfg  sdff sdf  CLASSY
sdgg asfert dfg asd insert asdgweg CLASSY
qwe asfer wrererw  werer wewer INSERT 

我想把这两个文件的内容都改成

File1.txt
asd asdsd INSERT asdasd Vintage
asddsdff sdf sdff sdf  CLASSY
sfre asfert asdd asd insert asdgweg 
qwe asfer wrererw  werer wewer INSERT Vintage

File2.txt
fhfgh asdsd insert asdasd Vintage
asddsdff dfg  sdff sdf  CLASSY
sdgg asfert dfg asd insert asdgweg Vintage
qwe asfer wrererw  werer wewer INSERT 

以下是我使用的命令,但它不能正常工作。你能帮我理解这个问题吗?

find /rootFolderPath -name "*.txt" | xargs grep -i insert -exec sed -i -e 'classy/Vintage/I' -- {} +

【问题讨论】:

  • @Yunnosch 抱歉打错了.. 我现在已经修正了

标签: regex linux shell sed find


【解决方案1】:

您可以使用gnu-sedfind 作为:

cd /rootFolderPath
find . -name '*.txt' -exec \
     sed -i '/\binsert\b/I{s/\bclassy\b/Vintage/gI;}' {} +

sed 命令的作用如下:

  • -i: 内联编辑
  • /\binsert\b/I:在一行中搜索字符串insertI\b 不区分大小写用于单词边界)
  • {s/\bclassy\b/Vintage/gI;}:如果在一行中找到insert,则将classy 替换为Vintage(同样,\bis for word boundaries,Iis for case insensitive andg` 用于全局搜索)

【讨论】:

  • 如果你能解释一下我将非常感激 sed -i '/insert/I{s/classy/Vintage/gI;}'
  • 在我的回答中添加了解释。
  • 好点@EdMorton。我在答案中添加了单词边界。
  • 您能否帮助我理解为什么它在与“xargs”一起使用时无法正常工作 find /rootFolderPath -name "*.txt" | xargs grep -i 插入
  • 我的回答中甚至没有grep
猜你喜欢
  • 2013-09-24
  • 2016-08-19
  • 2013-07-19
  • 1970-01-01
  • 1970-01-01
  • 2015-03-02
  • 2017-12-03
  • 2013-08-11
  • 1970-01-01
相关资源
最近更新 更多