LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   sed-with-loop, unexpected behavior (http://www.linuxquestions.org/questions/programming-9/sed-with-loop-unexpected-behavior-4175449995/)

danielbmartin 02-13-2013 10:01 AM

sed-with-loop, unexpected behavior
 
I've encountered a puzzling phenomenon while working on a different thread in this forum.

InFile1 ...
Code:

aaa
bbb
ccc

InFile2 ...
Code:

Hello
Tom
pat_start
line1
line2
pat_end
Goodbye
Tom

Code ...
Code:

W1='~'$(paste -sd"~" $InFile1)
paste -sd"~" $InFile2 > $Work2
# Note: \1 contains everything up to, but not including, pat_start.
#      \2 contains pat_start.
#      \3 contains everthing between pat_start up to but not including pat_end.
#      \4 contains pat_end.
#      \5 contains everything following pat_end.
sed -r '  s/(.*)(~pat_start)(.*)(~pat_end)(.*)/\1\2~~  \5/  ' $Work2
sed -r ':a s/(.*)(~pat_start)(.*)(~pat_end)(.*)/\1\2~~  \5/;ta' $Work2
sed -r '  s/(.*)(~pat_start)(.*)(~pat_end)(.*)/\1\2~~\4\5/  ' $Work2
sed -r ':a s/(.*)(~pat_start)(.*)(~pat_end)(.*)/\1\2~~\4\5/;ta' $Work2

For illustration the code shown has four successive seds.

The first one uses no loop and does not cite \4.
The second one uses a loop and does not cite \4.
The first and second sed generate the expected results, and they are identical.

The third one uses no loop and does cite \4.
The fourth one uses a loop and does cite \4.
The third sed generates the expected results.
I thought the third and fourth seds would generate identical results but that's not what happens.
The fourth one unlocks the keyboard and waits.

What have I done wrong?

Daniel B. Martin

firstfire 02-13-2013 12:25 PM

Hi, Daniel.

The ta command jumps to label :a if last substitution was successful. Your substitution is always successful, because you first break up the string into constituents (\1..\5) and then reconstruct the same string from them. Thus you have an infinite loop. Add l command in front of ta to make it obvious.

danielbmartin 02-13-2013 01:50 PM

Quote:

Originally Posted by firstfire (Post 4890907)
... Thus you have an infinite loop. ...

You are right. Thank you! SOLVED!

Daniel B. Martin


All times are GMT -5. The time now is 01:27 PM.