Saltar al contenido

~ / archivo / stackoverflow / 50911818

grep -l does not behave as expected on piping to xargs

StackOverflow · bash, grep, xargs · ayudé respuesta aceptada
  1. Carmageddon pregunta 2018-06-18 14:32

    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?

    • Sundeep 2018-06-18 14:36 can you try grep -lZ ... | xargs -0 ... ? that would rule out any issue due to characters like space/newline/etc in filenames
    • Sundeep 2018-06-18 14:37 also a suggestion: always use single quotes unless you need double quotes for interpolation.. grep '"tool":"SEETEST"'
    • Carmageddon 2018-06-18 14:46 Thanks, did both modifications - still same results :(
    • Carmageddon 2018-06-18 15:16 I think it only hapens if the grep command does not match anything, as seems to happen for SEETEST. Why is that?
    • simon3270 2018-06-18 15:17 Have you got a file with the name "*" in the current directory?
  2. Miguel Ortiz yo respuesta aceptada +1 2018-06-18 15:18

    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
    

← todos los hilos de StackOverflow