inotify and bash

前端 未结 3 1447
忘了有多久
忘了有多久 2020-12-08 14:35

I am trying to make a bash script with inotify-tools that will monitor a directory and alter all new files by removing lines containing \"EE\". Once altered it will move the

3条回答
  •  执念已碎
    2020-12-08 14:56

    By default, the text output from inotifywait -e CREATE is of form

         watched_filename CREATE event_filename
    

    where watched_filename represents /home/inventory/initcsv and event_filename represents the name of the new file.

    So, in place of your while inotifywait -e ... line, put:

        DIR=/home/inventory/initcsv
        while RES=$(inotifywait -e create $DIR); do
            F=${RES#?*CREATE }
    

    and in your sed line use $F as the Filein name. Note, the $(...) construction is posix-compatible form of process substitution (often done using backticks) and the ${RES#pattern} result is equal to $RES with the shortest pattern-matching prefix removed. Note, the last character of the pattern is a blank. [See update 2]

    Update 1 To handle file names that may contain whitespace, in the sed line use "$F" instead of $F. That is, use double quotes around the reference to value of F.

    The RES=... and F=... definitions do not need to use double quotes, but it is ok to use them if you like; for example: F=${RES#?*CREATE } and F="${RES#?*CREATE }" both will work ok when handling filenames containing whitespace.

    Update 2 As noted in Daan's comment, inotifywait has a --format parameter that controls the form of its output. With command

    while RES=$(inotifywait -e create $DIR --format %f .)
       do echo RES is $RES at `date`; done
    

    running in one terminal and command

    touch a aa; sleep 1; touch aaa;sleep 1; touch aaaa
    

    running in another terminal, the following output appeared in the first terminal:

    Setting up watches.
    Watches established.
    RES is a at Tue Dec 31 11:37:20 MST 2013
    Setting up watches.
    Watches established.
    RES is aaa at Tue Dec 31 11:37:21 MST 2013
    Setting up watches.
    Watches established.
    RES is aaaa at Tue Dec 31 11:37:22 MST 2013
    Setting up watches.
    Watches established.
    

提交回复
热议问题