How to copy files found with grep

后端 未结 1 1238
天涯浪人
天涯浪人 2021-01-12 03:52

I am running this command to find all my files that contain (with help of regex)\"someStrings\" in a tree directory.

grep -lir \'^beginString\' ./ -exec cp -         


        
相关标签:
1条回答
  • 2021-01-12 04:42

    Try this:

    find . -type f -exec grep -q '^beginString' {} \; -exec cp -t /home/user/DestinationFolder {} +
    

    or

    grep -lir '^beginString' . | xargs cp -t /home/user/DestinationFolder
    

    But if you want to keep directory structure, you could:

    grep -lir '^beginString' . | tar -T - -c | tar -xpC /home/user/DestinationFolder
    

    or if like myself, you prefer to be sure about kind of file you store (only file, no symlinks), you could:

    find . -type f -exec grep -l '^beginString' {} + | tar -T - -c |
        tar -xpC /home/user/DestinationFolder
    

    and if your files names could countain spaces and/or special characters, use null terminated strings for passing grep -l output (arg -Z) to tar -T (arg --null -T):

    find . -type f -exec grep -lZ '^beginString' {} + | tar --null  -T - -c |
        tar -xpC /home/user/DestinationFolder
    
    0 讨论(0)
提交回复
热议问题