I executed a command on Linux to list all the files & subfiles (with specific format) in a folder.
This command is:
ls -R | grep -e "\.txt$" -e "\.py$"
In an other hand, I have some filenames stored in a file .txt (line by line).
I want to show the result of my previous command, but I want to filter the result using the file called filters.txt
.
- If the result is in the file, I keep it
- Else, I do not keep it.
How can I do it, in bash, in only one line?
I suppose this is something like:
ls -R | grep -e "\.txt$" -e "\.py$" | grep filters.txt
An example of the file:
# filters.txt
README.txt
__init__.py
EDIT
I am trying to a file instead a list of argument because I get the error:
'/bin/grep: Argument list too long'
CodePudding user response:
You can use comm
:
comm -12 <(ls -R | grep -e "\.txt$" -e "\.py$" ) <(cat filters.txt)
This will give you the intersection of the two lists.
EDIT
It seems that ls
is not great for this, maybe find
Would be safer
CodePudding user response:
find . -type f | xargs grep $(sed ':a;N;$!ba;s/\n/\\|/g' filters.txt)
That is, for each of your files, take your filters.txt
and replace all newlines with \|
using sed
and then grep for all the entries.
Grep uses \|
between items when grepping for more than one item. So the sed
command transforms the filters.txt
into such a list of items to be used by grep
.
CodePudding user response:
grep -f filters.txt -r .
..where .
is your current folder.
CodePudding user response:
'/bin/grep: Argument list too long'
I executed a command on Linux to list all the files & subfiles (with specific format) in a folder.
This command is:
ls -R | grep -e ".txt$" -e ".py$" In an other hand, I have some filenames stored in a file .txt (line by line).
I want to show the result of my previous command, but I want to filter the result using the file called filters.txt.