简体   繁体   中英

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.

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)

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
$ 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM