使用sed保留来自字母范围正则表达式的字母?

时间:2014-02-26 03:35:13

标签: regex sed backreference

我正在使用:

cat this_file | sed ':a;N;$!ba;s/\n[a-z]/ [a-z]/g' > that_file

示例文字:

However the text \n
looks like this when it replaces the newline.\n

输出:

However the text [a-z]ooks like this when it replaces the newline.\n

这叫什么?关于我做错了什么的建议?

1 个答案:

答案 0 :(得分:3)

在模式中,[a-z]表示一个字符类。在替换中,它被替换为。您需要使用反向引用:

cat this_file | sed ':a;N;$!ba;s/\n\([a-z]\)/ \1/g' > that_file

此外,你可以避免无用的猫:

sed ':a;N;$!ba;s/\n\([a-z]\)/ \1/g' this_file > that_file