awk检查文件存在 [英] awk check file exists
问题描述
printf "2015-03-02|/home/user/.ssh/config\n2015-03-02|/home/user/Desktop/temp328\n" | awk -F\| 'if ( -f $2 ) { print $2}'
或
printf "2015-03-02|/home/user/.ssh/config\n2015-03-02|/home/user/Desktop/temp328\n" | awk -F\| '{if (system("test -f" $2)) print $2}'
/home/user/.ssh/config\n2015-03-02-存在
/home/user/.ssh/config\n2015-03-02 - exists
/home/user/Desktop/temp328-已删除
/home/user/Desktop/temp328 - removed
我只想打印现有文件,但是此命令不起作用.
I want print only exist files but this commands not working.
推荐答案
第二次尝试非常接近.在test -f
之后需要一个空格.
The second attempt was fairly close; you need a space after the test -f
.
base$ echo '2015|/etc/mtab
> 2015|/etc/ntab' | awk -F\| '{ if (system("test -f " $2)) print $2}'
/etc/ntab
您可能想要反转使用if (system(...)==0)
来获得所需的语义.另外,稍微优雅一点的是,Awk想要在括号之外使用一个条件,因此您可以避免使用显式的if
.
You probably want to invert to use if (system(...)==0)
to get the semantics you expected. Also, somewhat more elegantly, Awk wants a condition outside the braces, so you can avoid the explicit if
.
awk -F\| 'system("test -f " $2)==0 { print $2 }'
同意评论者的意见,认为使用Awk只是边缘问题.
Agree with commenters that using Awk for this is borderline nuts.
如果如注释中所示,如果您需要使用完全任意的文件名,则可以添加代码以引用任何特殊的shell:
If, as indicated in comments, you need to work with completely arbitrary file names, you can add code to quote any shell specials:
awk -F\| 'system ("test -f " gensub(/[^\/A-Za-z0-9]/, "\\\\&", "g", $2))==0 {
print $2 }' # caveat: gensub() is gawk only
...但是您的整体解决方案无法处理包含换行符或管道符的文件名(因为分别将它们用作记录分隔符和字段分隔符),因此再次放弃Awk并以另一种方法重新开始可能是前进的明智之路.
... but your overall solution does not cope with file names containing a newline character or a pipe character (since you are using those as record and field separators, respectively) so again, abandoning Awk and starting over with a different approach may be the sane way forward.
(替换中的字符类不完整;可以添加各种标点符号等,我可能遗漏了一些重要内容;但是在快速检查时,多余的反斜杠应该是无害的.如果您没有Gawk,请参见此处,和/或再次考虑放弃这种方法.)
(The character class in the substitution is incomplete; there are various punctuation characters etc which could be added, and I may be missing something significant; but on quick examination, the superfluous backslashes should be harmless. If you don't have Gawk, see here and/or, again, consider abandoning this approach.)
while IFS='|' read -r stuff filename; do
test -f "$filename" && echo "$filename"
done <<':'
2015|/etc/mtab
2016|/etc/ntab
2017|/path/to/file with whitespace in name
2018|/path/to/file\with[funny"characters*in(file'name|even pipes, you see?
:
(仍然没有换行符,但是其他都应该没问题.)
(Still no way to have a newline, but everything else should be fine.)
这篇关于awk检查文件存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!