how to write finding output to same file using awk command

前端 未结 6 1501
无人及你
无人及你 2021-01-31 15:46
awk \'/^nameserver/ && !modif { printf(\"nameserver 127.0.0.1\\n\"); modif=1 } {print}\' testfile.txt

It is displaying output but I want to wri

6条回答
  •  春和景丽
    2021-01-31 16:16

    Despite the fact that using a temp file is correct, I don't like it because :

    • you have to be sure not to erase another temp file (yes you can use mktemp - it's a pretty usefull tool)

    • you have to take care of deleting it (or moving it like thiton said) INCLUDING when your script crash or stop before the end (so deleting temp files at the end of the script is not that wise)

    • it generate IO on disk (ok not that much but we can make it lighter)

    So my method to avoid temp file is simple:

    my_output="$(awk '(PROGRAM)' source_file)"
    echo "$my_output" > source_file
    

    Note the use of double quotes either when grabbing the output from the awk command AND when using echo (if you don't, you won't have newlines).

提交回复
热议问题