0

So I have a command like: grep "\"tool\":\"SEETEST\"" * -l Which works great standalone - it prints out a list of JSON files generated for the selected tool in the current directory.

But then, if I were to pipe it to xargs ls like that: grep "\"tool\":\"SEETEST\"" * -l | xargs ls -lSh

It prints all the files in the current directory!

How do I make it print just the matched filenames and pipe them to ls sorted by size?

Carmageddon
  • 2,627
  • 4
  • 36
  • 56

1 Answers1

1

If there are not matches for xargs, then it will list all files in the current directory:

#----------- current files in the directory
mortiz@florida:~/Documents/projects/bash/test$ ls -ltr
    total 8
    -rw-r--r-- 1 mortiz mortiz 585 Jun 18 12:13 json.example2
    -rw-r--r-- 1 mortiz mortiz 574 Jun 18 12:14 json.example
#----------- using your command
mortiz@florida:~/Documents/projects/bash/test$ grep "\"title\": \"example\"" * -l
json.example
#-----------adding xargs to the previous command
mortiz@florida:~/Documents/projects/bash/test$ grep "\"title\": \"example\"" * -l | xargs ls -lSh
-rw-r--r-- 1 mortiz mortiz 574 Jun 18 12:14 json.example
#-----------adding purposely an error on "title" 
mortiz@florida:~/Documents/projects/bash/test$ grep "\"titleo\": \"example\"" * -l | xargs ls -lSh
total 8.0K
-rw-r--r-- 1 mortiz mortiz 585 Jun 18 12:13 json.example2
-rw-r--r-- 1 mortiz mortiz 574 Jun 18 12:14 json.example

If you want to use xargs and grep didn't return any match, then add "-r | --no-run-if-empty" that will prevent xargs to list all the files in the current directory:

grep "\"titleo\": \"example\"" * -l | xargs -r ls -lSh
Miguel Ortiz
  • 1,412
  • 9
  • 21