How to find and replace all percent signs, plus and pipes?

I have a document containing percent signs, plus and the handset. I want to replace them with code for use in TeX.

  • % becomes \textpercent .
  • + becomes \textplus .
  • | becomes \textbar .

This is the code I use, but it does not work:

 sed -i "s/\%/\\\textpercent /g" ./file.txt sed -i "s/|/\\\textbar /g" ./file.txt sed -i "s/\+/\\\textplus /g" ./file.txt 

How to replace these characters with this code?

+7
source share
3 answers

Test script:

 #!/bin/bash cat << 'EOF' > testfile.txt 1+2+3=6 12 is 50% of 24 The pipe character '|' looks like a vertical line. EOF sed -i -r 's/%/\\textpercent /g;s/[+]/\\textplus /g;s/[|]/\\textbar /g' testfile.txt cat testfile.txt 

Output:

 1\textplus 2\textplus 3=6 12 is 50\textpercent of 24 The pipe character '\textbar ' looks like a vertical line. 

This has already been suggested in a similar way with @tripleee, and I see no reason why this should not work. As you can see, my platform uses the same version of GNU sed as yours. The only difference from the @tripleee version is that I use the extended regular expression mode, so I need to either exit the channel or add its plus to the character class using [] .

+10
source
 nawk '{sub(/%/,"\\textpercent");sub(/\+/,"\\textplus");sub(/\|/,"\\textpipe"); print}' file 

Tested below:

 > echo "% + |" | nawk '{sub(/%/,"\\textpercent");sub(/\+/,"\\textplus");sub(/\|/,"\\textpipe"); print}' \textpercent \textplus \textpipe 
+3
source

Use single quotes:

 $ cat in.txt foo % bar foo + bar foo | bar $ sed -e 's/%/\\textpercent /g' -e 's/\+/\\textplus /g' -e 's/|/\\textbar /g' < in.txt foo \textpercent bar foo \textplus bar foo \textbar bar 
+2
source

All Articles