Reputation: 28022
I have a text file named "my_text_file.txt". I have another directory named "dir".
Now, "my_text_file.txt" has several lines and there is a file name in every line. I want to get only those lines of "my_text_file.txt" that have a filename that is also present in the directory "dir".
I tried something like
ls dir -1 | grep my_text_file.txt
but doesn't seem to work. Any help is appreciated.
Upvotes: 1
Views: 90
Reputation: 22225
You did not say which shell you are using. If you have bash
or zsh
, you can use
comm -12 <(ls dir) <(sort my_text_file.txt)
Whether this works with other shells too, I don't know.
Upvotes: 1
Reputation: 785058
You can use this while loop:
while IFS= read -r line; do
f="dir/$line"
[[ -f $f ]] && printf "%s\n" "$f"
done < my_text_file.txt
Or using xargs you can do:
xargs -0 ls -ld 2>/dev/null < <(awk -v ORS='\0' '{print ".foo/"$0}' my_text_file.txt)
Upvotes: 2
Reputation: 203324
$ 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
Upvotes: 1
Reputation: 174624
You need to pass oh
to 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
Upvotes: 1