简体   繁体   中英

Dealing with backreference in a sed command inside a shell script

I'm trying to make work a sed command inside of a shell script that takes variables while interacting with the user, but I can not make it work because of the backreference I use in it.... some help...?

Script:

echo "Origin language?\n"
read ol
echo "\nTarget language?\n"
read tl
echo "\ntmx file name?\n"
read file

then at the sed command I have tried these ways:

1.

sed -r "s/lang=\"$ol\">(.*)$/\1/g" "$file" > ${file}_${ol}.txt
sed -r "s/lang=\"$tl\">(.*)$/\1/g" "$file" > ${file}_${tl}.txt

2.

thisol = "<tuv xml:lang=\"$ol\">(.*)$"
thistl = "<tuv xml:lang=\"$tl\">(.*)$"

sed -r "s/$thisol/\1/g" "$file" > ${file}_${ol}.txt
sed -r "s/$thistg/\1/g" "$file" > ${file}_${tl}.txt

3.

thisol = "<tuv xml:lang=\"$ol\">(.*)$"
thistl = "<tuv xml:lang=\"$tl\">(.*)$"
that = "\\\1"

sed -r "s/$thisol/$that/g" "$file" > ${file}_${ol}.txt
sed -r "s/$thistg/$that/g" "$file" > ${file}_${tl}.txt

Based on the comment made by @EdMorton I could find the answer to this question, I had to modify a little bit the suggestion made by him, but at the end I realized that this was not what I needed, I should have done it with grep, any way here is the correct code to accomplish what is implied on the question, and the final grep command I used (which I learned from here )

sed command:

sed -r '/<tuv xml:lang='\"$ol\"'>/{N;/<seg>/{N;s/<tuv xml:lang='\"$ol\"'>\n\s+<seg>(.*)<\/seg>/\1/}}' "$file.tmx" > "${file}_${ol}.txt"

where:

/<tuv xml:lang='\\"$ol\\"'>/ the RegEx from the starting line

{N;/<seg>/ the RegEx from the finishing line

{N;s/<tuv xml:lang='\\"$ol\\"'>\\n\\s+<seg>(.*)<\\/seg> the searched complete RegEx

/\\1/ the backreference to the (.*) element

Grep command:

grep -Pzo "<tuv xml:lang=\"$ol\">\n\s+<seg>(.*)<\/seg>" "$file.tmx" > "${file}_${ol}.txt"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM