Bash 正确转义sed字符串
我有一个regex和替换模式,它们都在Notepad++中对我的输入数据进行了测试,并且工作正常。然而,当我将它们放入sed表达式中时,没有任何匹配项 以下是sed命令:Bash 正确转义sed字符串,bash,sed,escaping,Bash,Sed,Escaping,我有一个regex和替换模式,它们都在Notepad++中对我的输入数据进行了测试,并且工作正常。然而,当我将它们放入sed表达式中时,没有任何匹配项 以下是sed命令: # SEARCH = ([a-zA-Z0-9.]+) [0-9] (.*) # REPLACE = \2 (\1) sed -e 's/\([a-zA-Z0-9.]+\) [0-9] \(.*\)/\2 \(\1\)/g' 以下是数据样本: jdoe 1 Doe, John jad 1 Doe, Jane smith
# SEARCH = ([a-zA-Z0-9.]+) [0-9] (.*)
# REPLACE = \2 (\1)
sed -e 's/\([a-zA-Z0-9.]+\) [0-9] \(.*\)/\2 \(\1\)/g'
以下是数据样本:
jdoe 1 Doe, John
jad 1 Doe, Jane
smith 2 Smith, Jon
以及所需的输出:
Doe, John (jdoe)
Doe, Jane (jad)
Smith, Jon (smith)
我曾尝试在sed表达式中删除并向不同字符添加转义符,但要么没有得到匹配的转义符,要么出现以下情况:
sed: -e expression #1, char 42: invalid reference \2 on `s' command's RHS
如何正确地进行转义?我通常发现使用-r开关更容易,因为这意味着转义与大多数其他语言类似:
sed -r 's/([a-zA-Z0-9.]+) [0-9] (.*)/\2 (\1)/g' file1.txt
当不使用
-r
开关时,需要转义加号。其他人已经说过的一些警告和补充:
-r
选项是启用扩展正则表达式的GNU扩展。BSD派生的sed使用-E
's/\([a-zA-Z0-9.]\{1,\}\) [0-9] \(.*\)/\2 (\1)/g'
在任何与POSIX兼容的
sed
中,它都应该完全满足您的要求。如果你确实关心这些事情,考虑定义环境变量。使用AWK要简单得多……< /P>
$ sed -e 's/\([a-zA-Z0-9.].*\) [0-9] \(.*\)/\2 \(\1\)/g' file
Doe, John (jdoe)
Doe, Jane (jad)
Smith, Jon (smith)
cat test.txt | awk '{ print $3 " " $4 " " "("$1")" }'
输出:
Doe, John (jdoe)
Doe, Jane (jad)
Smith, Jon (smith)
见人啊