2016-08-14 115 views

回答

1
$ ls -1 tmp 
abc def 
bar 
foo 

$ cat file 
stuff 
abc def 
bar 
nonsense 
foo 

$ xargs -d'\n' -I {} -n 1 < file ls tmp/{} 2>/dev/null 
tmp/abc def 
tmp/bar 
tmp/foo 
2

你可以使用这个while循环:

while IFS= read -r line; do 
    f="dir/$line" 
    [[ -f $f ]] && printf "%s\n" "$f" 
done < my_text_file.txt 

或者使用xargs的,你可以这样做:

xargs -0 ls -ld 2>/dev/null < <(awk -v ORS='\0' '{print ".foo/"$0}' my_text_file.txt) 
+0

O.O - 我觉得有点太多了? –

+1

而不是循环目录中所有文件的可能大集合,这是更好地循环通过文本文件中的文件,并避免grep。 – anubhava

+1

有道理;假定文件比目录列表小。 –

1

你需要传递oh到grep:

$ ls 
1.txt 2.txt 3.txt files.txt 

$ cat files.txt 
1.txt 
2.txt 
3.txt 
hello.txt 

$ for n in *; do grep -oh $n files.txt; done 
1.txt 
2.txt 
3.txt 
+0

对于名称包含空格和/或通配符和/或正则表达式元字符和/或名称与其他文件部分匹配的文件(1.txt将匹配11.txt)的文件,将会失败 –

1

你没有说你正在使用哪个外壳。如果你有bashzsh,您可以使用

comm -12 <(ls dir) <(sort my_text_file.txt) 

这是否也与其他贝壳也一样,我不知道。

相关问题