用__text__替换%(text)s

时间:2014-03-22 17:13:23

标签: bash replace sed

关于sed / awk的一些问题:

1. How to replace %(text)s with __text__

Example:

    %(vehicle)s -> __vehicle__

第二个问题:

2. How to make reverse operation: replace __text__ with %(text)s ?

Example:  

    __vehicle__ -> %(vehicle)s

1 个答案:

答案 0 :(得分:1)

$ cat test.txt
How to replace %(text)s with __text__
How to make backward operation: replace __text__ with %(text)s

$ sed 's#%(\([^)]*\))s#__\1__#g' test.txt
How to replace __text__ with __text__
How to make backward operation: replace __text__ with __text__

$ sed 's#__\([^_]*\)__#%(\1)s#g' test.txt
How to replace %(text)s with %(text)s
How to make backward operation: replace %(text)s with %(text)s

请注意,捕获组parantheses需要在sed中转义。