In previous articles, we explored the main features of the xargs utility. Now, let’s dive into several practical examples to better understand its application in real-world scenarios.
Deleting Files: Convenience and Flexibility
One of the most common use cases for xargs is deleting groups of files found using the find command. Consider a scenario where we need to delete all files with the .log extension:
$ find . -type f -name "*.log" -print0 | xargs -0 rm -f
In this example, -print0 ensures proper handling of filenames containing spaces. The find command separates lines with null bytes, and xargs processes them using the -0 flag, preventing errors due to spaces in paths.
Deleting Files by Exclusion
Another scenario involves deleting all files except those matching a specific pattern. For example, to delete all files except .txt files:
$ find . -type f ! -name "*.txt" -print0 | xargs -0 rm -f
This command recursively deletes all files that do not match the .txt pattern.
Bulk Renaming Files
Using xargs, we can also rename files efficiently. Suppose we need to change the extension of .md files to .html:
$ ls *.md | sed -e "s/.md$/.html/" | xargs -L 1 mv
This example applies the sed command to change the extension, then passes the results to mv via xargs.
A more compact approach using cut is:
$ ls *.md | cut -d. -f1 | xargs -I{} mv {}.md {}.html
Here, cut extracts the filename without the extension, and xargs renames it to .html.
Changing File Permissions
When modifying file permissions, xargs helps automate the process. For instance, to change the group ownership to developers for all files owned by root, use:
$ sudo find ./ -type f -user root -print | xargs sudo chgrp developers
This command modifies the group for all files belonging to root.
Deleting Old Files
To remove files older than 30 days, such as temporary files in /var/tmp, execute:
$ find /var/tmp -type f -mtime +30 -print0 | xargs -0 rm -f
Here, find locates files older than 30 days, and xargs removes them.
Archiving Files
To create an archive of all .jpg images, use the following command:
$ find . -name "*.jpg" -type f -print0 | xargs -0 tar -cvzf images_archive.tar.gz
This command creates a tar.gz archive containing all .jpg files in the current directory.
Formatting Output
Sometimes, we need to format output into a single line for further processing. For example, to list all users in the system: