基本上我有一个“数据库”,我的脚本中有一个函数来安装应用程序。所以这个函数在这里搜索:
is-program-installed=
并在“程序”安装完成时发生“1”:
is-program-installed= 1
但如果找不到该行并且我希望该函数写一个会怎么样?
function dbmarktrue () {
table=${1?Usage: dbmarktrue $editdbtable}
sed -e "/^is-$table-installed=/ s/.$/1/" -i database.txt
}
答案 0 :(得分:4)
我会查看文件并执行替换;如果发生,请设置一个标志。最后,在处理完整个文件后,如果没有设置这样的标志,则打印它:
awk -v replace="is-program-installed=1" '
$0 == "is-program-installed=" {$0=replace; seen=1}1;
END {if (!seen) print replace}' a
它不存在:
$ 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
它存在:
$ 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
像往常一样,awk
替换原始文件,您可以将输出重定向到临时文件,然后移动到原始文件:
awk '...' file > tmp_file && mv tmp_file file
使用&&
,如果mv
退出时出错,我们会确保awk
命令未执行。