awk:如果找不到模式,则在文件末尾添加一些文本

MHP*_*MHP 4 awk text-processing

使用awk,我们如何才能在底部添加文本,只有在文件中找不到某个模式时

这不起作用:

awk '{if ($0 !~ /pattern/) {print}; END {print "someText"}}' file
Run Code Online (Sandbox Code Playgroud)

文件很小,不到1MB。

αғs*_*нιη 9

另一种awk方法在大文件大小上要快一点,一旦找到模式就退出,如果找不到模式,则将某些内容附加到文件中。

awk '/pattern/{found=1; exit}; END{ if(!found) print "append" >>FILENAME }' infile
Run Code Online (Sandbox Code Playgroud)

或者使用grep

<infile grep -q pattern || echo 'appending...' >>infile
Run Code Online (Sandbox Code Playgroud)


Adm*_*Bee 5

以下应该有效:

awk '/pattern/ {found=1} {print} END{if (!found) print "someText"}' file
Run Code Online (Sandbox Code Playgroud)

这将先验打印整个文件({print}无条件规则),然后查找模式。如果找到,它会设置一个标志({found=1}条件为/pattern/,相当于$0 ~ /pattern/)。如果在文件末尾未设置该标志,则将"someText"打印 。

您可以将输出重定向到新文件,如下所示

awk ' <see above> ' file > newfile
Run Code Online (Sandbox Code Playgroud)

或者,如果您有较新版本的 GNU awk,请使用“就地”编辑功能(小心!):

awk -i inplace ' <see above> ' file
Run Code Online (Sandbox Code Playgroud)