Suppose there is a text (assembly code)

st.w    av,d15
ld.w    d15,av

Suppose we want to match it with grep. We can use this pattern:


Note: we use .* to match the register names. In the future these register names can change.

Suppose we want to use special regex for register names. We add special @reg keyword:


Then we add a prepossessing function for the grep pattern, where we replace all the special keywords to actual regex patterns:

preprocess_pattern () {
    local result=$1
    # Replace @reg to exact regex pattern [a..d][0..15].
    # Add other replacements (if need).
    echo "$result"

Then we call preprocess_pattern() before executing grep:

pattern="$(preprocess_pattern $pattern)"
if ! grep -Pzo $pattern code.asm > /dev/null
    echo "grep #$i failed (pattern: "$pattern")"

It works, but we want more.

We want to add @preg, which is previous register.


Now the question: where is (and how) to add the logic, which after the each occurrence of @reg saves the matched value (in our case d15) in the special stack / buffer and after each occurrence of the @preg retrieves the matched value from the stack / buffer and checks this value against the value of the @preg?

In other words: how to write pattern for matching data with context sensitive elements? Is it possible at all with grep?

If yes (i.e. possible) then how to describe this context sensitivity in the pattern?

If no (i.e. impossible) then how else to solve this challenge?

  • you won't be able to do it like this this. each line is matched independently
    – n.caillou
    Apr 17, 2020 at 18:28

1 Answer 1


What you are trying to achieve might be achievable by grep + regex, but that's going to be complicated. Your task needs a full fledged script or a program in some language.

Following features of different commands can be helpful

  1. Grep Context: the only context grep provides is number of lines before and after a matched line [-A, -B, -C (combination of previous two)]
  2. Awk and Sed : using these you can search for text within 2 patterns.

But again, this is going to be complicate. From what I understand, you are trying to write a parser of somekind, so you should research and try to use the write tool before jumping into writing complicated commands.

You must log in to answer this question.

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