Linux Commands and Scripts

Linux 10 Useful Commands of Xargs

In this article, we will learn more about Linux 10 Useful commands of Xargs.

xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is /bin/echo) one or more times with any initial-arguments followed by items read from standard input. Blank lines on the standard input are ignored.

Syntax of the xargs command

xargs [options] [command [initial-arguments]]

1. Copy the file into multiple directories

# echo ./dir1/ ./dir2/ | xargs -n 1 cp -v ~/some-doc

Using above command you can copy any file like some-doc into multiple directories like dir1 and dir2

2. Generate the compact list of all Linux user accounts on the system

# cut -d: -f1 < /etc/passwd | sort | xargs

Above command will display all users list present in the Linux system. You can verify all the user you have created and also system users.

3. Instruct to xargs to read items from file

# xargs -a some-file

This command will display the contents of the file. It works as a cat command.

4. Rename all files or sub-directories

# find Documents -depth | xargs -n 1 rename -v 's/(.*)\/([^\/]*)/$1\/\L$2/' {} \;

Above command will rename files or directories to lowercase.

5. Delete files expect some extension which will mentions in the command

# find . -type f -not -name '*gz' -print0 | xargs -0 -I {} rm -v {}

This command will remove all the files expect the extension you mention to not move it like *.gz.

6. Remove directory recursively

# find . -name "tool" -type d -print0 | xargs -0 /bin/rm -v -rf "{}"

Above command will find directory and remove it recursively in current working directory.

7. Remove same name file

# find . -name "file" -type f -print0 | xargs -0 /bin/rm -v -rf "{}"

Above command will find same named file in current working directory and remove it.

8. Count numbers of lines/words/characters

# ls *file* | xargs wc

Above command will display numbers of lines,words and characters in each file in the list.

9. Convert multi-line output from ls command into single line

# ls -1 Documents | xargs

10. Find files with specific extension and archive them using tar

# find Documents -name "*.docx" -type f -print0 | xargs -0 tar -cvzf documents.tar.gz

Above command will find mentioned extension and archive it in to tar like we have mentioned *.docx file extension, so it will find files with that extension and archive it in to documents.tar.gz.

In this article we have seen Linux 10 Useful commands of Xargs.

[Need assistance to fix this error or install tools? We’ll help you.]

Related Articles