How to grep and execute a command (for every match)

前端 未结 6 1961
慢半拍i
慢半拍i 2020-12-14 00:18

How to grep in one file and execute for every match a command?

File:

foo
bar
42
foo
bar

I want to execute to execute for example

6条回答
  •  庸人自扰
    2020-12-14 00:52

    There is an interesting command in linux for that: xargs, It allows You to use the output from previous command(grep, ls, find, etc.) as the input for a custom execution but with several options that allows You to even execute the custom command in parallel. Below some examples:

    Based in your question, here is how to print the date with format "%s.%N" for each "foo" match in file.txt:

    grep "foo" file.txt | xargs -I {} date +%s.%N
    

    A more interesting use is creating a file for each match, but in this case if matches are identical the file will be override:

    grep "foo" file.txt | xargs -I {} touch {}
    

    If You want to concatenate a custom date to the file created

    grep "foo" file.txt | xargs -I {} touch "{}`date +%s.%N`"
    

    Imagine the matches are file names and You want to make a backup of them:

    grep "foo" file.txt | xargs -I {} cp {} "{}.backup"
    

    And finally for xargs using the custom date in the backupName

    grep "foo" file.txt | xargs -I {} cp {} "{}`date +%s.%N`"
    

    For more info about options like parallel execution of xargs visit: https://en.wikipedia.org/wiki/Xargs and for date formats: https://www.thegeekstuff.com/2013/05/date-command-examples/

    Extra I have found also a normal for command useful in this scenarios It is simpler but less versatile below are the equivalent for above examples:

    for i in `grep "foo" test.txt`; do date +%s.%N; done
    for i in `grep "foo" test.txt`; do touch ${i}; done
    for i in `grep "foo" test.txt`; do touch "${i}`date +%s.%N`"; done
    for i in `grep "foo" test.txt`; do cp ${i} "${i}.backup2"; done
    for i in `grep "foo" test.txt`; do cp ${i} "${i}.backup2`date +%s.%N`"; done
    

    Have Fun!!!

提交回复
热议问题