我正在尝试编写一个使用perl查找和替换字符的bash函数。我写了以下函数:
find_replace() {
perl -p -i -e "s/$1/$2/g" "$3"
}
它现在无法正常工作,我认为因为$ 1和$ 2被它们周围的引号转义(据我所知,这是perl语法的一部分,需要在那里)。
有关如何使此功能工作的任何提示(或更好的方法来编写它以避免此问题)?
编辑:
根据Barmar的建议,这是我尝试运行该函数时的输出:
dholtz$ find_replace \001 , revenue_by_offer_tid
+ find_replace 001 , revenue_by_offer_tid
+ perl -p -i -e ''\''s/001/,/g'\''' revenue_by_offer_tid
++ update_terminal_cwd
++ local 'SEARCH= '
++ local REPLACE=%20
++ local PWD_URL=file://Dave-Mac-2.local/Users/dholtz
++ printf '\e]7;%s\a' file://Dave-Mac-2.local/Users/dholtz
dholtz$ head revenue_by_offer_tid
+ head revenue_by_offer_tid
Friday00228686050.0
Friday00228690410.0
Friday017438366585.040000000000004
Friday017438366591.3200000000000003
Friday017438366600.12
Friday0174383666114.759999999999962
Friday017438371407.440000000000006
Friday0174383815118.599999999999977
Friday017438382221.5600000000000005
Friday017438383663.480000000000002
预期输出为:
Friday,0,0,22,86860,50.0
Friday,0,0,22,86904,10.0
Friday,0,1,7438,36658,5.040000000000004
Friday,0,1,7438,36659,1.3200000000000003
Friday,0,1,7438,36660,0.12
Friday,0,1,7438,36661,14.759999999999962
Friday,0,1,7438,37140,7.440000000000006
Friday,0,1,7438,38151,18.599999999999977
Friday,0,1,7438,38222,1.5600000000000005
Friday,0,1,7438,38366,3.480000000000002
答案 0 :(得分:0)
反斜杠阻止报价正确处理
find_replace() {
perl -p -i -e "s/$1/$2/g" "$3"
}
答案 1 :(得分:0)
bash手册告诉:
未引用的反斜杠(\)是转义字符。它保留了 下一个字符的字面值,......
所以,正如我们在上面的输出中看到的那样,你的命令
find_replace \001 , revenue_by_offer_tid
被视为(\只是不必要地保留0)
find_replace 001 , revenue_by_offer_tid
- 不是你想要的。要保留反斜杠,必须在输入的命令行中引用它,e。克。
find_replace \\001 , revenue_by_offer_tid