Abhishek Shivkumar Abhishek Shivkumar - 1 year ago 74
Bash Question

I have to get only those lines in a text file that contain the filename of the files in another directory

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.

Answer Source

You can use this while loop:

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

Or using xargs you can do:

xargs ls -1d 2>/dev/null < <(sed 's~^~dir/~' my_text_file.txt)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download