In-place processing with grep

前端 未结 9 2095
庸人自扰
庸人自扰 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:12

    Store in a variable and then assign it to the original file:

    A=$(cat aux.log | grep 'Something') && echo "${A}" > aux.log
    
    0 讨论(0)
  • 2020-12-25 12:14

    Most installations of sed can do in-place editing, check the man page, you probably want the -i flag.

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

    No, in general it can't be done in Unix like this. You can only create/truncate (with >) or append to a file (with >>). Once truncated, the old contents would be lost.

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

    Take a look at my slides "Field Guide To the Perl Command-Line Options" at http://petdance.com/perl/command-line-options.pdf for more ideas on what you can do in place with Perl.

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

    In general, this can't be done. But Perl has the -i switch:

    perl -i -ne 'print if /SomeRegEx/' myfile.txt
    

    Writing -i.bak will cause the original to be saved in myfile.txt.bak.

    (Of course internally, Perl just does basically what you're already doing -- there's no special magic involved.)

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

    cat myfile.txt | grep 'sometext' > myfile.txt

    This will find sometext in myfile.txt and save it back to myfile.txt, this will accomplish what you want. Not sure about regex, but it does work for text.

    0 讨论(0)
提交回复
热议问题