0

Is there a perl one-liner that could replace some text between 2 strings (inclusive)? For example in the text below I need to replace everything between 'rrpv_bits = 2' and 'options.cacheline_size' with 'num_sets = 512' everywhere in the text where these 2 tag strings are found. So the original text would look like the desired one.

Original:

    repl = ReplacementPolicy(rrpv_bits = 2,
                             ins = 2,
                             num_sets = l2_cache.size.getValue() /
                             options.l2_assoc / options.cacheline_size,
                             assoc = options.l2_assoc)

Desired:

    repl = ReplacementPolicy(num_sets = 512,
                             assoc = options.l2_assoc)

If a perl one-liner can't do that then is there anything else (Linux, one-liner) that can?

Thank you

1 Answer 1

1

If they always exist together, a perl one-liner:

perl -0777 -pe 's/rrpv_bits = 2.*?options\.cacheline_size/num_sets = 512/gs' file.txt > newfile.txt

However, this approach is likely too greedy. What would happen if the first boundary matches but not the second in a ReplacePolicy call? Then the regex will just eat up all the lines until it finds a second ReplacePolicy that does contain the end condition.

Therefore, to protect against this, we can limit the characters between boundary conditions to only allow balanced parenthesis. This would lock the matching to within the parameters of a ReplacePolicy:

perl -0777 -pe 's/rrpv_bits = 2((?:[^()]*|\((?1)\))*)options\.cacheline_size/num_sets = 512/gs;' file.txt > newfile.txt

Explanation:

Switches:

  • -0777: Slurp the entire file
  • -p: Creates a while(<>){...; print} loop for each “line” in your input file.
  • -e: Tells perl to execute the code on command line.
Sign up to request clarification or add additional context in comments.

1 Comment

Yes they do. amazing. Thank you so much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.