编辑一行,找不到就创建

Edit a line and create it if it's not found

基本上我得到了一个 "database" 和我的脚本中的一个函数来安装应用程序。所以这里的这个函数搜索:

is-program-installed=

并在 "program" 安装完成时出现“1”:

is-program-installed= 1

但是如果找不到该行并且我希望该函数写入一个会怎样?

function dbmarktrue () {

table=${1?Usage: dbmarktrue $editdbtable}

sed -e "/^is-$table-installed=/ s/.$/1/" -i database.txt
}

我会检查文件并执行替换;如果发生这种情况,请设置一个标志。最后,在处理完整个文件后,如果未设置此类标志,则打印它:

awk -v replace="is-program-installed=1" '
       [=10=] == "is-program-installed=" {[=10=]=replace; seen=1}1;
       END {if (!seen) print replace}' a

测试

它不存在:

$ cat a
hello
$ awk -v replace="is-program-installed=1" '[=11=] == "is-program-installed=" {[=11=]=replace; seen=1}1; END {if (!seen) print replace}' a
hello
is-program-installed=1

存在:

$ cat a
hello
is-program-installed=
$ awk -v replace="is-program-installed=1" '[=12=] == "is-program-installed=" {[=12=]=replace; seen=1}1; END {if (!seen) print replace}' a
hello
is-program-installed=1

像往常一样,awk要替换原始文件,您可以将输出重定向到一个临时文件,然后移动到原始文件:

awk '...' file > tmp_file && mv tmp_file file

通过使用 &&,我们确保 mv 命令不会在 awk 因错误退出时执行。