xargs

Reads a list from the standard input and executes the commands sequentially. This is a very useful command, and I think it is a must-have command for executing file operations in the CUI. It is a very useful command, and I think it is essential for file manipulation in CUI.

XARGS(1) BSD General Commands Manual

NAME
     xargs -- construct argument list(s) and execute utility

SYNOPSIS
     xargs [-0opt] [-E eofstr] [-I replstr [-R replacements]] [-J replstr]]
           [-L number] [-n number [-x]] [-P maxprocs] [-s size]]
           [-P maxprocs] [-s size]] [-utility [argument ...]]

github

  • The file in jupyter notebook format on github is here .

google colaboratory

  • To run it in google colaboratory here xargs/xargs_nb.ipynb)

environment

The author’s OS is macOS, and the options are different from those of Linux and Unix commands.

When you actually run the command, the leading ! and %%bash in the first line.

!sw_vers
ProductName: Mac OS X
ProductVersion: 10.14.6
BuildVersion: 18G95
!bash --version
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin18)
Copyright (C) 2007 Free Software Foundation, Inc.

Usage examples

This is a very useful command and has many uses. Here are some examples of commands that I often use.

Use ls to rename files in bulk.

ls | grep XXXX | xargs -I{} cp {} {}.bk

Search for files containing XXXX and take a backup of those files, using I{} to get the arguments before passing them down the pipe.

%%bash
echo "Create three files with the string "temp"."
echo "temp1" > temp1
echo "temp2" > temp2
echo "temp3" > temp3

ls | grep temp
Create three files with the string "temp".
temp1
temp2
temp3

Create a backup file for these three files.

%%bash
ls | grep temp | xargs -I{} cp {} {}.bk

echo "<file>"
ls | grep temp
<file>
temp1
temp1.bk
temp2
temp2.bk
temp3
temp3.bk

and the backup will be created in bulk.

Bulk delete files containing a specific string

Deletes all files that contain the string abc. Very useful.

%%bash
echo "Create 5 files with the name abc"
echo "abc" > abc1
echo "abc" > abc2
echo "abc" > abc3
echo "abc" > abc4
echo "abc" > abc5

ls | grep abc
Create five files with the name "abc
abc1
abc2
abc3
abc4
abc5
ls | grep abc | xargs -I{} rm {}
! ls | grep abc
abc4 abc5

and the five files with the string abc were deleted.

Do a recursive search for filenames with XXX in them and replace them all with YYY.

grep XXX -rl . | xargs sed -i.bk -e 's/XXX/YYYY/g'

Do a recursive search for filenames with XXX in them and replace all with YYY

find . / -type f | sed 'p;s/aaa/bbb/' | xargs -n2 mv

As mentioned above, this command is very easy to use, so please use it according to your own needs to improve your work efficiency.

Typical options

You can use xargs -I{} to get the result before the pipe as an argument, which is very useful.

  • I{}