29

我正在尝试使用 inotify-tools 制作一个 bash 脚本,该脚本将监视目录并通过删除包含“EE”的行来更改所有新文件。更改后,它将文件移动到另一个目录

    #!/bin/sh
    while inotifywait -e create /home/inventory/initcsv; do
      sed '/^\"EE/d' Filein > fileout #how to capture File name?
      mv fileout /home/inventory/csvstorage
    fi
    done

请帮忙?

4

3 回答 3

25

默认情况下,文本输出inotifywait -e CREATE的形式是

     watched_filename CREATE event_filename

其中 watched_filename代表/home/inventory/initcsvevent_filename代表新文件的名称。

因此,代替您的while inotifywait -e ...行,输入:

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

并在您的sed$F中用作Filein名称。请注意,$(...)构造是 posix 兼容形式的进程替换(通常使用反引号完成),${RES#pattern}结果等于$RES删除了最短的模式匹配前缀。请注意,模式的最后一个字符是空白。 [见更新 2]

更新 1要处理可能包含空格的文件名,请在 sed 行中使用"$F"而不是$F. 也就是说,在对 的值的引用周围使用双引号F

RES=...andF=...定义不需要使用双引号,但是如果你喜欢使用它们是可以的;例如: 在处理包含空格的文件名时F=${RES#?*CREATE },两者都可以正常工作。F="${RES#?*CREATE }"

更新 2如 Daan 的评论中所述,inotifywait有一个--format控制其输出形式的参数。有命令

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

在一个终端和命令中运行

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

在另一个终端中运行,在第一个终端中出现以下输出:

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.
于 2011-09-24T23:25:04.180 回答
13

的输出inotifywait形式为:

filename eventlist [eventfilename]

如果您的文件名可以包含空格和逗号,则解析起来会很棘手。如果它只包含“健全”的文件名,那么你可以这样做:

srcdir=/home/inventory/initcsv
tgtdir=/home/inventory/csvstorage
inotifywait -m -e create "$directory" |
while read filename eventlist eventfile
do
    sed '/^"EE/d'/' "$srcdir/$eventfile" > "$tgtdir/$eventfile" &&
    rm -f "$srcdir/$eventfile
done
于 2011-09-24T23:35:57.810 回答
1

引用 inotifywait 的手册页:

inotifywait will output diagnostic information on standard error and event information  on
   standard  output.  The event output can be configured, but by default it consists of lines
   of the following form:

   watched_filename EVENT_NAMES event_filename

   watched_filename
          is the name of the file on which the event occurred.  If the file is a directory, a
          trailing slash is output.

换句话说,它将文件名打印到标准输出。因此,您需要从标准输出中读取它们并对其进行操作以执行您想要执行的操作。

于 2011-09-24T23:25:21.493 回答