Question

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
Was it helpful?

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_*

OTHER TIPS

ls p_*

and you could also do

rm p_*

Straight forward rm p_* should work to remove all files starting with p_.

To display files starting with p_, you could use ls p_*. You can also use ls -l or -a options with p_* to view other details of these files.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top