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

查看:72
本文介绍了使用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:仅列出匹配的文件名

      • -l: only list matching filenames

      -R:在所有给定目录中进行递归搜索

      -R: search recursively through all given directories

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

      -Z: use \0 as record separator

      "\.jpg|\.png|\.gif":匹配字符串".jpg"".gif"".png"

      .:在当前目录中开始搜索

      .: start the search in the current directory

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

      xargs: execute a command with the stdin as argument

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

      • -0: use \0 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 : s 团队编辑管理员

      • -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天全站免登陆