0

rem par str how to remove few strings

I need to remove rem, par, str from the whole line

  • 2
    Provide the input and desired output. And what did you try so far? – Romeo Ninov Jan 11 '23 at 05:13
  • See the example below. Is this what you want? [edit] the question and make it [mre](https://stackoverflow.com/help/minimal-reproducible-example). It will be closed otherwise. – Vladimir Botka Jan 11 '23 at 06:42

1 Answers1

2

The main point of this rebus is to remove the strings only and leave the words starting and potentially ending by these strings untouched. The solution is starting and ending the regexp by matching an empty string at word boundary \b. This will keep the words starting and ending by these strings untouched. Add \s? to match one space after the string if exists. This will match the strings at the end of the line as well.

Use the module replace. For example, given the file

shell> cat /tmp/test.txt 
rem par str how to remove few strings

Put the strings you want to remove into a list

  remove_strings: [rem, par, str]

Iterate the list

    - replace:
        path: /tmp/test.txt
        regexp: '\b{{ item }}\b\s?'
        replace: ''
      loop: "{{ remove_strings }}"

gives

shell> cat /tmp/test.txt 
how to remove few strings

  • Example of a complete playbook for testing
- hosts: localhost
  vars:
    remove_strings: [rem, par, str]
  tasks:
    - replace:
        path: /tmp/test.txt
        regexp: '\b{{ item }}\b\s?'
        replace: ''
      loop: "{{ remove_strings }}"
Vladimir Botka
  • 5,138
  • 8
  • 20