In-place processing with grep

前端 未结 9 2096
庸人自扰
庸人自扰 2020-12-25 11:53

I\'ve got a script that calls grep to process a text file. Currently I am doing something like this.

$ grep \'SomeRegEx\' myfile.txt > myfile.txt.temp
$ m         


        
相关标签:
9条回答
  • 2020-12-25 12:27

    To edit file in-place using vim-way, try:

    $ ex -s +'%!grep foo' -cxa myfile.txt
    

    Alternatively use sed or gawk.

    0 讨论(0)
  • 2020-12-25 12:28

    sponge (in moreutils package in Debian/Ubuntu) reads input till EOF and writes it into file, so you can grep file and write it back to itself.

    Like this:

    grep 'pattern' file | sponge file
    
    0 讨论(0)
  • 2020-12-25 12:33

    Perl has the -i switch, so does sed and Ruby

    sed -i.bak -n '/SomeRegex/p' file
    
    ruby -i.bak -ne 'print if /SomeRegex/' file
    

    But note that all it ever does is creating "temp" files at the back end which you think you don't see, that's all.

    Other ways, besides grep

    awk

    awk '/someRegex/' file > t && mv t file
    

    bash

    while read -r line;do case "$line" in *someregex*) echo "$line";;esac;done <file > t && mv t file
    
    0 讨论(0)
提交回复
热议问题