0

I have a file t.txt

For example, assuming the file contain values like below. Values changes and do not know what it will change to. I want just to grep what inside the file.

[session] cat t.txt
John
Alex
Danny

I want to run a command like this to grep for all of them:

ls -lart | grep -e John -e Alex -e Danny

How i can read those values from t.txt file and put them in pattern as above using -e. I want to grep for whatever values in the file and grep for them all. Those values changes all the time and i want to automate this.

for i in cat t.txt do ls -lart | grep $i done

I know the above will work. I do not want loop. I want to use grep patter using -e.

Help me guys..

tink
  • 14,342
  • 4
  • 46
  • 50
John
  • 3
  • 2
  • 2
    See [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers). – pjh Jun 07 '23 at 00:19
  • 1
    See: [Why *not* parse `ls`?](http://unix.stackexchange.com/questions/128985/why-not-parse-ls) – Cyrus Jun 07 '23 at 05:04
  • Your approach would also match a file named `Alexis` or `JohnDoe`. Is this intended? – user1934428 Jun 07 '23 at 07:59
  • Update your example to include substrings and regexp metachars so we can see how you want those handled as its usually trivial to match what you want but harder to not match similar text you don't want, see [how-do-i-find-the-text-that-matches-a-pattern](https://stackoverflow.com/questions/65621325/how-do-i-find-the-text-that-matches-a-pattern). Also, `ls ... |` is a bad starting point, see https://mywiki.wooledge.org/ParsingLs. – Ed Morton Jun 07 '23 at 13:46

2 Answers2

1

Assuming those names are one per line:

ls -lart | grep -f t.txt

instead of looping.

tink
  • 14,342
  • 4
  • 46
  • 50
  • 1
    This did it. Thank you so much.. – John Jun 07 '23 at 00:17
  • Welcome @John ... Please feel free to accept the response if it solved your problem. – tink Jun 07 '23 at 00:19
  • @John Should you really want the `-e pattern` thing here's a slow and convoluted alternative :D `ls -lart | grep $(awk '{printf "-e %s ", $0}' t.txt)` – tink Jun 07 '23 at 00:30
0

To get all directory entries which have one of the lines in t.txt as a substring:

shopt -s extglob
ls *+($(paste -s -d '|' t.txt))*

To get all directory entries which are exactly one of the lines in t.txt

shopt -s extglob
ls +($(paste -s -d '|' t.txt))

Turning on extglob enables the +(...) globbing, and the paste command separates the elements inside the globbing list by vertical bar.

user1934428
  • 19,864
  • 7
  • 42
  • 87