Reputation: 309
Basically i got a "database", and a function in my script to install applications. So this function down here searches for:
is-program-installed=
and happens "1" when "program" installation finishes:
is-program-installed= 1
but what happens if the line is not found and i want that function to write one?
function dbmarktrue () {
table=${1?Usage: dbmarktrue $editdbtable}
sed -e "/^is-$table-installed=/ s/.$/1/" -i database.txt
}
Upvotes: 1
Views: 40
Reputation: 290355
I would go through the file and perform the replacement; if it happens, set a flag. And finally, after the whole file was processed, print it if such flag was not set:
awk -v replace="is-program-installed=1" '
$0 == "is-program-installed=" {$0=replace; seen=1}1;
END {if (!seen) print replace}' a
It was not present:
$ cat a
hello
$ awk -v replace="is-program-installed=1" '$0 == "is-program-installed=" {$0=replace; seen=1}1; END {if (!seen) print replace}' a
hello
is-program-installed=1
It was present:
$ cat a
hello
is-program-installed=
$ awk -v replace="is-program-installed=1" '$0 == "is-program-installed=" {$0=replace; seen=1}1; END {if (!seen) print replace}' a
hello
is-program-installed=1
As usual, awk
to replace the original file you can redirect the output to a temporary file and then move to the original:
awk '...' file > tmp_file && mv tmp_file file
By using &&
we make sure the mv
command is not executed if the awk
exits with an error.
Upvotes: 4