How to update/rewrite a file?

Dm114

Well-known member
To update a file, the classical MD method consists in rewriting it line by line from a string variable. It's ok but a bit long and sometimes it skips the 1st or first 2 lines (probably a matter if delay between erasing the old version -if any- and writing the first records).

Does a shell command exist (symetrical to "cat") to write a file from a variable?
 
Last edited:

FrameXX

Well-known member
Bash:
echo "first line\nsecond line" > /storage/emulated/0/documents/test.txt
Bash:
echo "[lv=string]" > /storage/emulated/0/documents/test.txt
 

RSF

Well-known member
Different possible approach if your edits are fairly simple (e.g. to replace a string everywhere in the file, with another string): you might try the sed utility in your shell action, vs. updating via MacroDroid variables etc. sed is one of those useful, albeit somewhat cryptic, old Unix/Linux commands...
 

Dm114

Well-known member
Bash:
echo "first line\nsecond line" > /storage/emulated/0/documents/test.txt
Bash:
echo "[lv=string]" > /storage/emulated/0/documents/test.txt
Sorry @FrameXX but it doesn't work on multi-line files containing whatever special characters such as" (double quote)
 

Dm114

Well-known member
Different possible approach if your edits are fairly simple (e.g. to replace a string everywhere in the file, with another string): you might try the sed utility in your shell action, vs. updating via MacroDroid variables etc. sed is one of those useful, albeit somewhat cryptic, old Unix/Linux commands...
Unfortunately edits can be of any form, any length, any where in the file. So, as far as I understood the sed command, I'm afraid it won't work in my case.
Thanks anyway.
 

FrameXX

Well-known member
Sorry @FrameXX but it doesn't work on multi-line files containing whatever special characters such as" (double quote)

It does. Replace any special character with \ before it. Like so.

Bash:
echo "first line\nsecond line \"quote\"" > /storage/emulated/0/documents/test.txt
 

RSF

Well-known member
Another alternative: have you tried MacroDroid's Files > Write to File action? You can specify a variable whose contents should be written to the file (in this example, a variable called "line"):
Screenshot 2022-05-19 3.08.56 PM.png
 

Dm114

Well-known member
It does. Replace any special character with \ before it. Like so.

Bash:
echo "first line\nsecond line \"quote\"" > /storage/emulated/0/documents/test.txt
You're right in theory but it will slow down drastically execution to check every line on big files.
 

Dm114

Well-known member
Another alternative: have you tried MacroDroid's Files > Write to File action? You can specify a variable whose contents should be written to the file (in this example, a variable called "line"):
View attachment 2755
Shame on me! 🤒
I use it frequently but always to write line by line and never thought to write the whole file. It seems to work fine.
Thanks for this simple advice 👍
 
Top