Friday, April 15, 2022

[SOLVED] How to "give priority" to certain pattern instead of others in sed?

Issue

I have this sed filter:

/.*[1-9][0-9][0-9] .*/{
        s/.*\([1-9][0-9][0-9] .*\)/\1/
}

/.*[1-9][0-9] .*/{
        s/.*\([1-9][0-9] .*\)/\1/
}

/.*[0-9] .*/{    # but this is always preferred/executed
        s/.*\([0-9] .*\)/\1/
}

The problem is that the first two are more restrictive, and they are not executed because the last third one is more "powerfult" because it includes the first two. Is there a way to make sed take the first two, with a "priority order"? Like

if the first matches
    do first things
elif the second matches
    do second things
elif the third matches
    do third things

Solution

if .. elif

sed is a simple GOTO language. Research b and : commands in sed.

/.*[1-9][0-9][0-9] .*/{
        s/.*\([1-9][0-9][0-9] .*\)/\1/
         b END
}

/.*[1-9][0-9] .*/{
        s/.*\([1-9][0-9] .*\)/\1/
        b END
}

/.*[0-9] .*/{    # but this is always preferred/executed
        s/.*\([0-9] .*\)/\1/
}

: END


Answered By - KamilCuk
Answer Checked By - Katrina (WPSolving Volunteer)