Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Limit output to 5 items

grep -r 'foo' | xargs sed -i 's/foo/bar/g'

I am using this command to replace all items of foo to bar.
However, I want to only replace foo with bar in the first 5 files. Somehow I would need to cut the output of grep to just the first 5 items, or get xargs to only get the first 5 items from the output.

Thanks!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

you can use the head command to limit the output of grep to the first 5 results before passing it to xargs.

Here’s the modified command:

grep -r -l 'foo' | head -n 5 | xargs sed -i 's/foo/bar/g'

For items 5 to 10, you can use a combination of head and tail commands to achieve that.

Here’s the command to process items 5 to 10:

grep -r -l 'foo' | head -n 10 | tail -n 6 | xargs sed -i 's/foo/bar/g'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading