删除含有特殊字符的字符串

删除含有特殊字符的字符串

test我有一个类似于以下内容的文件:

hello
my
name
<h6>test morning</h6>
is
bob

我知道我会使用:

sed -i -- 's/name//g' test

要从文件中删除name,但如何删除<h6>test morning</h6>

该字符串可以位于文件中的任何位置,并且该文件可以是类似 a.css.html文件的任何内容。

答案1

对于这种情况,您可以使用任何字符/。例如

sed -i 's|<h6>test morning</h6>||g' test

对于字符串马赫模式,您应该转义第一个

sed -i '\|<h6>test morning</h6>|s///g' test

如果你的/模式很少,可能很容易直接逃脱它

sed -i '/<h6>test morning<\/h6>/s///g' test

答案2

Perl 来救援!

在 Perl 中,可以在模式部分使用变量,并且可以使用引用元(或相应的\Q转义)转义特殊字符:

REPLACE='<h6>test morning</h6>' perl -pe 's/\Q$ENV{REPLACE}//'

答案3

使用 Perl,您也可以对文件和目录路径应用相同的更改...这个变成 bash 函数的代码片段是过去 5 年中专业和业余项目中最常用的代码部分...

        # some initial checks the users should set the vars in their shells !!!
        test -z $dir_to_morph && exit 1 "You must export dir_to_morph=<<the-dir>> - it is empty !!!"
        test -d $dir_to_morph || exit 1 "The dir to morph : \"$dir_to_morph\" is not a dir !!!"
        test -z $to_srch && exit 1 "You must export to_srch=<<str-to-search-for>> - it is empty !!!"
        test -z $to_repl && exit 1 "You must export to_repl=<<str-to-replace-with>> - it is empty !!!"

        echo "INFO dir_to_morph: $dir_to_morph"
        echo "INFO to_srch:\"$to_srch\" " ;
        echo "INFO to_repl:\"$to_repl\" " ;
        sleep 2

        echo "INFO START :: search and replace in non-binary files"
        #search and replace ONLY in the txt files and omit the binary files
        while read -r file ; do (
           #debug echo doing find and replace in $file
           echo "DEBUG working on file: $file"
           echo "DEBUG searching for $to_srch , replacing with :: $to_repl"

           # we do not want to mess with out .git dir
           # or how-to check that a string contains another string
           case "$file" in
              *.git*)
              continue
              ;;
           esac
           perl -pi -e "s#\Q$to_srch\E#$to_repl#g" "$file"
        );
        done < <(find $dir_to_morph -type f -not -exec file {} \; | grep text | cut -d: -f1)

        echo "INFO STOP  :: search and replace in non-binary files"

        #search and repl %var_id% with var_id_val in deploy_tmp_dir
        echo "INFO search and replace in dir and file paths dir_to_morph:$dir_to_morph"

        # rename the dirs according to the pattern
        while read -r dir ; do (
           perl -nle '$o=$_;s#'"\Q$to_srch\E"'#'"$to_repl"'#g;$n=$_;`mkdir -p $n` ;'
        );
        done < <(find $dir_to_morph -type d|grep -v '.git')

        # rename the files according to the pattern
        while read -r file ; do (
           perl -nle '$o=$_;s#'"\Q$to_srch\E"'#'"$to_repl"'#g;$n=$_;rename($o,$n) unless -e $n ;'
        );
        done < <(find $dir_to_morph -type f -not -path "*/node_modules/*" |grep -v '.git'

相关内容