DEV Community

Cover image for Terminal 101 - Xargs
Rubin
Rubin

Posted on

Terminal 101 - Xargs

xargs is a command in Unix and Unix-like operating systems used to build and execute commands from standard input. It's particularly handy when you want to pass the output of one command as arguments to another command. Here are a few common use cases with examples:

  • Deleting multiple files:
find . -name "*.txt" | xargs rm
Enter fullscreen mode Exit fullscreen mode

This command finds all files with a .txt extension in the current directory and its subdirectories, then passes them to xargs, which in turn executes rm (remove) command on each file.

  • Creating backups:
find /path/to/files -type f -print | xargs -I {} cp {} /path/to/backup
Enter fullscreen mode Exit fullscreen mode

This command finds all files in /path/to/files, then uses xargs to copy each file to /path/to/backup.

  • Running commands in parallel:
cat list_of_urls.txt | xargs -P 5 -n 1 wget -q
Enter fullscreen mode Exit fullscreen mode

This command reads a list of URLs from list_of_urls.txt, then uses xargs with -P option to run wget with up to 5 parallel processes, downloading each URL.

  • Searching for files containing specific text:
grep -rl "search_term" /path/to/search | xargs sed -i 's/search_term/replace_term/g'
Enter fullscreen mode Exit fullscreen mode

This command finds all files in /path/to/search containing "search_term", then uses xargs to pass each file to sed, replacing "search_term" with "replace_term".

Top comments (0)