2017年6月2日 星期五

[Linux 常見問題] Piping find results to rm

Source From Here 
Question 
I'm trying to work out a command which deletes sql files older than 15 days. How do I pipe the output of find to command rm

How-To 
What you want is to use the output of find as arguments to rm
# find -type f -name '*.sql' -mtime +15 | xargs rm

xargs is the command that "converts" its standard input into arguments of another program, or, as they more accurately put it on the man page, 
build and execute command lines from standard input

Note that if file names can contain whitespace characters, you should correct for that: 
# find -type f -name '*.sql'
./test name.sql
./test2.sql


// -print0: print the full file name on the standard output, followed by a null character
# find -type f -name '*.sql' -print0
./test name.sql./test2.sql

// -0, --null: Input items are terminated by a null character instead of by whitespace, and the quotes and
// backslash are not special (every character is taken literally).

# find -type f -name '*.sql' -mtime +15 -print0 | xargs -0 rm

But actually, find has a shortcut for this: the -delete option: 
# find -type f -name '*.sql' -mtime +15 -delete

Please be aware of the following warnings in man find
Warnings: Don't forget that the find command line is evaluated
as an expression, so putting -delete first will make find try to
delete everything below the starting points you specified. When
testing a find command line that you later intend to use with
-delete, you should explicitly specify -depth in order to avoid
later surprises. Because -delete implies -depth, you cannot
usefully use -prune and -delete together.

PS. Note that piping directly to rm isn't an option, because rm doesn't expect filenames on standard input. 

Supplement 
Linux 系統 xargs 指令範例與教學

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...