Search code examples
bashunixgrepls

ls: grep files with name pattern into one line


I have some files that start with a prefix, which I will call p_ in this context. Let's say I have three files with the prefix named p_1, p_2, p_3. How do I grep a list of these files through something like GNU ls into one space-separated string?

Example:

$ ls | grep p_
p_1 <\
p_2 < --- Remove '\n' after the file name and replace with space
p_3 </

# So that we get...
$ ls [.. solution goes here ..]
p_1 p_2 p_3

Now say, if we want to rm all files with the prefix, we can use:

$ rm $(ls [.. solution goes here ..])

Which will be the same as:

$ rm p_1 p_2 p_3

Solution

  • Use | xargs echo:

    $ rm $(ls | grep p_ | xargs echo)
    

    Or more directly, | xargs rm:

    $ ls | grep p_ | xargs rm
    

    Or even more directly, since arguments can be separated by any whitespace, which includes newlines:

    $ rm $(ls | grep p_)
    

    I personally like globbing:

    $ rm p_*