bash - Escaping character only when it appears between parenthesis -


i've searched around internet , tried many combinations can not seem work.

i trying write script creates latex table code. works fine until have ampersand inside 1 of values, e.g.,

{1702} & {12389122} & {topic 1 online quiz} & {1.7} & {2} & {83.3} \\\hline  {1702} & {12389122} & {topic 2 & 3 online q...} & {1.9} & {2} & {93.3} \\\hline {1702} & {12389122} & {topic 4 online quiz} & {} & {2} & {} \\\hline {1702} & {12389122} & {topic 5 online quiz ...} & {} & {2} & {} \\\hline 

i need able read in input.txt file containing data , output result output.txt file, same data apart in line 2 need escape ampersand, e.g.,

{1702} & {12389122} & {topic 1 online quiz} & {1.7} & {2} & {83.3} \\\hline  {1702} & {12389122} & {topic 2 \& 3 online q...} & {1.9} & {2} & {93.3} \\\hline {1702} & {12389122} & {topic 4 online quiz} & {} & {2} & {} \\\hline {1702} & {12389122} & {topic 5 online quiz ...} & {} & {2} & {} \\\hline 

but escape ampersand(s) appear between {}

i think may have been closer earlier, last attempt following:

sed 's/\({[a-za-z0-9. _]*\)\(\&\)\([a-za-z0-9. _]*}.*\)/\1\\\2\3/' input.txt > output.txt 

any appreciated.

the below code works me

sed 's/{\([^}]*\)&\([^}]*\)}/{\1\\\&\2}/g' input.txt > output.txt 

explanation: /g flag of sed command performs substitution across entire line. in absence of /g flag, sed performs first substitution per line.

in 'search' field of sed command, starting {, looking characters not } , stop @ &. looking characters again not } until encounter first }'. restricted search ensures find&that strictly within closest{and}. replacing same escaped&`.

note: replace 1 & within given pair of curly braces. if have more 1 &, need modify regular expression.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -