我必须只获取文本文件中包含另一个目录中文件的文件名的那些行
I have to get only those lines in a text file that contain the filename of the files in another directory
我有一个名为 "my_text_file.txt" 的文本文件。我有另一个名为 "dir".
的目录
现在,"my_text_file.txt"有好几行,每行都有一个文件名。我只想获取 "my_text_file.txt" 的那些行,这些行的文件名也存在于目录 "dir".
中
我试过
ls dir -1 | grep my_text_file.txt
但似乎不起作用。感谢任何帮助。
您可以使用这个 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='[=11=]' '{print ".foo/"[=11=]}' my_text_file.txt)
您需要将 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
$ 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
您没有说明您使用的是哪个 shell。如果你有 bash
或 zsh
,你可以使用
comm -12 <(ls dir) <(sort my_text_file.txt)
这是否也适用于其他 shell,我不知道。
我有一个名为 "my_text_file.txt" 的文本文件。我有另一个名为 "dir".
的目录现在,"my_text_file.txt"有好几行,每行都有一个文件名。我只想获取 "my_text_file.txt" 的那些行,这些行的文件名也存在于目录 "dir".
中我试过
ls dir -1 | grep my_text_file.txt
但似乎不起作用。感谢任何帮助。
您可以使用这个 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='[=11=]' '{print ".foo/"[=11=]}' my_text_file.txt)
您需要将 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
$ 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
您没有说明您使用的是哪个 shell。如果你有 bash
或 zsh
,你可以使用
comm -12 <(ls dir) <(sort my_text_file.txt)
这是否也适用于其他 shell,我不知道。