1

I am interested if there's a more elegant solution to the one posted below.

[]$ find ./abc -type f -exec sed -n 's/test/best/pg' {} + ; find ./abc -type f -exec sed -i 's/test/best/g' {} +

The first find sed command prints all found patterns to console. The second find sed command actually substitutes the patterns within file.

The problems I have encountered:

  1. sed -n -i (cannot have multiple command line modifier/arguments) -? someone confirm?

  2. sed does not have a native modifier to print results prior to substitution -? had trouble finding a solution, maybe it exists, and the command can be modified (i.e. below will output nothing, and substitute behind your back!).

    find ./abc -type f -exec sed -i 's/test/best/pg' {} +  
    
perror
  • 3,171
  • 7
  • 33
  • 45

2 Answers2

2

Well, you don't need to have two separate find commands:

find abc -type f -exec sed -n 's/test/best/pg' {} + -exec sed -i 's/test/best/g' {} +

... and you don't need the ./ in front of abc.

  • Because that doesn't work.  It's the worst of both worlds — it doesn't print anything, and it deletes all the lines in the file that don't match `test`. – G-Man Says 'Reinstate Monica' Dec 02 '15 at 23:32
  • Oh, god. That's brainless enough I'm just going to delete it. Here: `sed -ni '/test/w /dev/tty s//best/g; p'` (w/ a newline after `tty`) – jthill Dec 02 '15 at 23:40
  • Note that jthill edited his/her comment since I posted my first response; the first version was `sed -ni 's/test/best/pg' \{} +`.  The revised version, `sed -ni '/test/{p;s//best/g}' \{} +`, is even worse: it still deletes all the lines in the file that don't match `test`, but *it doesn't even do the requested substitution on the lines that do!* – G-Man Says 'Reinstate Monica' Dec 02 '15 at 23:41
  • `sed -ni '/test/w /dev/tty s//best/g; p'` doesn't work either.  If you think you have an answer, you should *post an answer* rather than critiquing a correct answer; comments are not good for multi-line text.  If you meant to have a newline rather than a space after `/dev/tty`, it ***still doesn't work*** (suggestion: *try* commands before you post them) but is coming close to answers that were posted to [How to report “sed” in-place changes](http://unix.stackexchange.com/a/200576/80216) six months ago. – G-Man Says 'Reinstate Monica' Dec 02 '15 at 23:50
  • You're right, of course. Started out brainless, continued that way. My apologies. – jthill Dec 02 '15 at 23:57
1

If you're on GNU/anything you can

find abc -type f -exec sed -i 's/test/best/gw /dev/fd/2' {} +

but in your text you mentioned wanting to print results prior to substitution, not sure what "results" means there but

find abc -type f -exec sed -i '/test/w /dev/fd/2
                               s//best/g' {} +

prints the lines that will change prior to substitution.

jthill
  • 2,671
  • 12
  • 15