I have file, say test.s that contains several trivial infinite loops:

        branch .LBB7_7

Labels may be totally different, but all are like .LBB\d_\d+

I want some neat way to process such things with grep or sed one-liner.

Now I am doing this way. First I calculate all labels:

grep -oP 'branch .\KLBB\d_\d+' minimize.s

And then in bash for loop I looking up label with one line below with grep -A1 "^.$i:" and checking its output for branch $i

Can I do better (without explicit bash processing with grep only)?

1 Answer 1


try this:

$ cat ip.txt
        branch .LBB7_7
    mov a, b
        branch .LBB8_3

$ grep -zoP '(\.LBB\d_\d+):\s*branch\h+\1\n' ip.txt
        branch .LBB7_7
  • -z will use ASCII NUL as record separator instead of default newline character. Assuming your input doesn't have NUL characters, this will cause whole file to be slurped
  • (\.LBB\d_\d+) capture label, but can't specify to match at start of line
  • :\s*branch\h+\1\n condition to check for infinite loop

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .