我正在尝试使用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请帮帮忙?
发布于 2011-09-25 07:25:04
默认情况下,从inotifywait -e CREATE输出的文本格式为
watched_filename CREATE event_filename其中watched_filename表示/home/inventory/initcsv,event_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=...和F=...定义不需要使用双引号,但是如果您喜欢也可以使用双引号;例如: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-25 07:35:58
inotifywait的输出是这样的:
filename eventlist [eventfilename]如果您的文件名可以包含空格和逗号,这将很难解析。如果它只包含“sane”文件名,那么你可以这样做:
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-25 07:25:21
引用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.换句话说,它将文件名打印到标准输出。因此,您需要从标准输出中读取它们,并对它们进行操作以执行您想要执行的操作。
https://stackoverflow.com/questions/7542430
复制相似问题