Replacing “#”, “$”, “%”, “&”, and “_” with “\#”, “\$”, “\%”, “\&”, and “\_”

前端 未结 4 1865
臣服心动
臣服心动 2020-12-31 10:02

I have a plain text document, which I want to compile inside LaTeX. However, sometimes it has the characters, \"#\", \"$\", \"%\", \"&\", and \"_\". To compile properly

4条回答
  •  渐次进展
    2020-12-31 10:29

    sed -i 's/\#/\\\#/g' ./file.txt
    sed -i 's/\$/\\\$/g' ./file.txt
    sed -i 's/\%/\\\%/g' ./file.txt
    sed -i 's/\&/\\\&/g' ./file.txt
    sed -i 's/\_/\\\_/g' ./file.txt
    

    You don't need the \ on the first (search) string on most of them, just $ (it's a special character, meaning the end of a line; the rest aren't special). And in the replacement, you only need two \\, not three. Also, you could do it all in one with several -e statements:

    sed -i.bak -e 's/#/\\#/g'  \
               -e 's/\$/\\$/g' \
               -e 's/%/\\%/g'  \
               -e 's/&/\\&/g'  \
               -e 's/_/\\_/g' file.txt
    

    You don't need to double-escape anything (except the \\) because these are single-quoted. In your grep, bash is interpreting the escape on the $ because it's a special character (specifically, a sigil for variables), so grep is getting and searching for just the $, which is a special character meaning the end of a line. You need to either single-quote it to prevent bash from interpreting the \ ('\$', or add another pair of \\: "\\\$". Presumably, that's where you're getting the\` from, but you don't need it in the sed as it's written.

提交回复
热议问题