使用 sed 和 grep/egrep 进行搜索和替换 [英] Using sed and grep/egrep to search and replace

查看:28
本文介绍了使用 sed 和 grep/egrep 进行搜索和替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 egrep -R 后跟一个包含大约 10 个联合的正则表达式,例如:<代码>.jpg |.png |.gif 等.这很好用,现在我想用 .bmp

I am using egrep -R followed by a regular expression containing about 10 unions, so like: .jpg | .png | .gif etc. This works well, now I would like to replace all strings found with .bmp

我正在考虑类似的事情

egrep -lR ".jpg|.png|.gif" . | sed "s/some_expression/.jpg/" file_it_came_form

所以这里的问题是我如何在 sed 中做一个类似的联合正则表达式,以及我如何告诉它保存对它获得输入的文件的更改.

so the issue here is how do I do a similar union regular expression in sed and how do I tell it to save the changes to the file that it got the input from.

推荐答案

使用这个命令:

egrep -lRZ ".jpg|.png|.gif" . 
    | xargs -0 -l sed -i -e 's/.jpg|.gif|.png/.bmp/g'

  • egrep:使用扩展正则表达式查找匹配行

    • egrep: find matching lines using extended regular expressions

      • -l:只列出匹配的文件名

      -R:递归搜索所有给定目录

      -R: search recursively through all given directories

      -Z:使用作为记录分隔符

      ".jpg|.png|.gif":匹配字符串 ".jpg", ".gif 之一"".png"

      ".jpg|.png|.gif": match one of the strings ".jpg", ".gif" or ".png"

      .:在当前目录开始搜索

      xargs:以标准输入为参数执行命令

      xargs: execute a command with the stdin as argument

      • -0:使用 作为记录分隔符.这对于匹配 egrep-Z 并避免被输入文件名中的空格和换行符所迷惑很重要.

      • -0: use as record separator. This is important to match the -Z of egrep and to avoid being fooled by spaces and newlines in input filenames.

      -l:每个命令使用一行作为参数

      -l: use one line per command as parameter

      sed:stream editor

      • -i:用输出替换输入文件,不做备份

      • -i: replace the input file with the output without making a backup

      -e:使用以下参数作为表达式

      -e: use the following argument as expression

      's/.jpg|.gif|.png/.bmp/g':替换所有出现的字符串 ".jpg"".gif"".png"".bmp"

      's/.jpg|.gif|.png/.bmp/g': replace all occurrences of the strings ".jpg", ".gif" or ".png" with ".bmp"

      这篇关于使用 sed 和 grep/egrep 进行搜索和替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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