Modifying a file

I can easily use a file module to delete the existing file and create a new one with File1 content.
But I want to modifile the file using lineinfile or replace. Please help.
Thanks

Existing File:
This is an existing file / $ % with invalid characters &*() Blahh

Expected Output:
File1

I can easily use a file module to delete the existing file and create a new one with File1 content.
But I want to modifile the file using lineinfile or replace. Please help.
Thanks

Existing File:
This is an existing file / $ % with invalid characters &*() Blahh

Expected Output:
File1

      If you can define it in regexp you can do it.

you cant…cos a lot of characters there… i cant find a way how to delete them in regex.

you cant...cos a lot of characters there.. i cant find a way how to delete
them in regex.

Can you explain to us exactly what you want the command to identify?

Are there, for example, certain characters which should never appear in a file,
and if they do, you want the content to be replaced?

If that's not the case, then what do you want to recognise and replace? How
would you tell a person what to do?

please don’t CC me.

  • name: Delete Everything in the file
    lineinfile:
    path: /tmp/filetomodify
    regexp: “*”
    line: This is for File1

state: absent

Existing File:
This is an existing file / $ % with invalid characters &*() Blahh, a lot of characters here… Everything in this file should be delete and be replace by “This is for File1”

Expected Output:
This is for File1

My solution is below. But I would like the lineinfile as solution not as below.
Thanks

  • name: Delete file
    file:
    path: /tmp/filetomodify

state: absent

  • name: Add the line
    file:
    path: /tmp/filetomodify

content: This is for File1

- name: Delete Everything in the file
lineinfile:
path: /tmp/filetomodify
regexp: "*"
line: This is for File1
state: absent

Existing File:
This is an existing file / $ % with invalid characters &*() Blahh, a lot of characters here.. Everything in this file
should be delete and be replace by "This is for File1"

Expected Output:
This is for File1

My solution is below. But I would like the lineinfile as solution not as below.
Thanks

lineinfile is definitely the wrong module if you are going to update the whole file. Try copy or content module.

Regards
        Racke

I know, lineinfile. I was thinking of file or copy module. Like just absent/present and content as argument. My question is, how about replace? you think the module replace can help?
Thanks