Escape comma in ansible win_lineinfile module

Viewed 164

I have a PowerShell script file: C:\Workdir\createLog.ps1

I want to comment out this line Remove-Item -Force ($Path + '*' + $Suffix); in the script

I use ansible to do it automatically, using win_lineinfile module. The code is like this:

- name: Comment out content
    win_lineinfile:
      path: "C:\\Workdir\\createLog.ps1"
      regexp: '^(\s+)Remove-Item -Force \(\$Path \+ \'\*\' \+ \$Suffix\);'
      line: '$1# Remove-Item -Force ($Path + '*' + $Suffix);'
      backrefs: yes

But it returns an error, because '*' cannot pass as string at regexp

1 Answers

It seems you want to find lines with any amount of whitespace before a line with the Remove-Item -Force ($Path + '*' + $Suffix); contents and add a # + space after the leading whitespace.

You can use

regexp: '^(\s*)(Remove-Item -Force \(\$Path \+ \'\*\' \+ \$Suffix\);)'
line: '\1#\2'
backrefs: yes

See this regex demo. \1#\2 in the backrefs parameter specify that the replacement should be Group 1 value + # + Group 2 value.

The pattern matches

  • ^ - start of string/line here
  • (\s*) - Group 1 (\1): zero or more whitespaces
  • (Remove-Item -Force \(\$Path \+ \'\*\' \+ \$Suffix\);) - Group 2 (\2): Remove-Item -Force ($Path + '*' + $Suffix); string.

You might want to replace the literal spaces with \s+ (one or more) or \s* (zero or more whitespace) to match any kind of whitespace.

Related