【问题标题】:search and replace string on multiple files from unix terminal从 unix 终端搜索和替换多个文件上的字符串
【发布时间】:2011-11-24 01:27:34
【问题描述】:

我们正在将代码库中的所有静态 html 页面转换为 php 页面。第一步是将所有 .html 文件扩展名更改为 .php(我已经这样做了)。第二步是更新每个 html 页面中的所有链接以指向新的 php 页面。

(例如,在 index.php 中,我有指向 contact.html 和 about-us.html 的链接。现在,由于我们已将每个 .html 文件扩展名替换为 .php,我们需要将 contact.html 更改为 contact。 php,同样,about-us.html 到 about-us.php)。

我现在要做的是在多个文件中搜索特定的字符串。 (在许多文件中搜索“contact.html”,例如 index.php、index2.php、index3.php 等。)之后,将所有这些文件中的所有“contact.html”替换为“contact.php” ”。

我对unix命令行不熟悉,到目前为止我在论坛上看到过其他人的类似问题,但不太明白哪一个可以帮助我实现我想要的。我正在使用 cygwin,如果可能的话,我需要在没有 perl 脚本的情况下解决这个问题,因为我没有安装它。我需要尝试使用 sed、grep、find 或其他任何一个。

所以,如果你们中的任何人认为这是重复的,请指向我那里的相关帖子。感谢您的宝贵时间。

【问题讨论】:

    标签: unix sed terminal replace


    【解决方案1】:

    这应该可以工作(在这里找到:http://www.mehtanirav.com/search-and-replace-recursively-using-sed-and-grep/):

    for i in `find . -type f` ; do sed "s/html/php/g" "$i" >> "$i.xx"; mv "$i.xx" "$i"; done
    

    【讨论】:

      【解决方案2】:

      试试这个:

      find . -name '*.html' -exec sed -i 's/\.html/\.php/g' "{}" \;

      它将查找当前和子目录中以.html 结尾的所有文件,并在每个文件上运行sed 以将.html 替换为.php

      更多详情请见http://content.hccfl.edu/pollock/unix/findcmd.htm

      【讨论】:

      • 这适用于 GNU sed;由于sed 的非标准-i 选项,它不一定适用于其他Unix 平台。
      • @JonathanLeffler:是的,我们被宠坏了。 :-)
      【解决方案3】:

      在我的 Mac 上,我必须向 -i 选项添加一个参数:要添加到名称的扩展名(在这种情况下,什么都没有,所以文件就地存储)。

      find . -name '*.html' -exec sed -i '' 's/\.html/\.php/g' "{}" \;
      

      【讨论】:

        【解决方案4】:
        You can certainly use ack to select your files to update. For example,
        to change all "foo" to "bar" in all PHP files, you can do this from 
        the Unix shell: 
        
        perl -i -p -e's/foo/bar/g' $(ack -f --php)
        

        来源:man ack

        【讨论】:

        • 此解决方案在 OS X 上保留了文件结尾的换行符,而 sed 将删除它们。 (不过我不得不brew install ack
        【解决方案5】:

        这对我有用:

        find . -type f -print0 | xargs -0 sed -i 's/str1/str2/g'

        【讨论】:

          【解决方案6】:

          以下脚本可以帮助替换文件中的字符串:

          #!/bin/bash
          echo -e "please specify the folder where string has need to be replaced: \c"
          read a
          echo -e "please specify the string to be replaced: \c"
          read b
          echo -e "please specify the string: \c"
          read c
          find $a -type f -exec sed -i 's/'"$b"'/'"$c"'/g' {} \; > /dev/null 2>&1
          if [ $? -eq 0 ]
          then
          echo "string has been replaced..."
          else                                                                         echo "String replacement has been failed"
          exit0
          fi
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-01-02
            • 1970-01-01
            • 2017-01-06
            • 1970-01-01
            • 1970-01-01
            • 2023-03-26
            • 2020-01-06
            • 1970-01-01
            相关资源
            最近更新 更多