Page tree

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The -I{} specifies that the arguments by results from ls will be placed in the location of the {} called the replacement string. In fact you can use whatever variable name you want instead of {}. For example, the following will also workchanging {} to varX also works,

Code Block
languagebash
ls | xargs -t -IvarX md5 varX
md5 file1.txt
MD5 (file1.txt) = d41d8cd98f00b204e9800998ecf8427e
md5 file2.txt
MD5 (file2.txt) = d41d8cd98f00b204e9800998ecf8427e
md5 file3.txt
MD5 (file3.txt) = d41d8cd98f00b204e9800998ecf8427e

...

When using xargs it will not work with special characters like apostrophe in file names.

To get around this limitation use the find command's -print0 option in combination with -0 which handles special characters white space, quote marks, backslashes, blanks and/or newlines,

Code Block
languagebash
find . -print0 | xargs -0 -I{} echo {}

Note using xarg's -0 "The GNU find -print0 option produces input suitable for this mode." it probably is because it is meant to be used together.

This is because "ls" produces slightly different output from "find .". Here is an example,

Code Block
languagebash
# Data I am working with
ls
11 My Baby's Got To Pay the Rent 1.m4a			6 Habits (Stay High) [Hippie Sabotage Remix] 1.txt
11 My Baby's Got To Pay the Rent 1.txt			Tin's file.txt
11 Summertime Sadness 1.m4a				hello
11 The Troubles 1.m4a					pwd
12 Canoeing (Katie and Alex's Theme) 1.m4a		test123
 
# Apostrophe kills xargs here
xargs: unterminated quote
 
# -0 by itself does not solve the problem
ls | xargs -0 -I{} echo {}
{}


# Now it works.
find . -print0 | xargs -0 -I{} echo {}
.
./11 My Baby's Got To Pay the Rent 1.m4a
./11 My Baby's Got To Pay the Rent 1.txt
./11 Summertime Sadness 1.m4a
./11 The Troubles 1.m4a
./12 Canoeing (Katie and Alex's Theme) 1.m4a
./6 Habits (Stay High) [Hippie Sabotage Remix] 1.txt
./hello
./pwd
./test123
./Tin's file.txt


# Remove a file to show -0 works with smaller data set,
rm test123
 
# -0 by itself now works, but making any file names longer or adding back test123 breaks it
ls | xargs -0 -I{} echo {}
{}
Kitchen-iMac:tmp tin.pham$ ls | xargs -0 -I{} echo {}
11 My Baby's Got To Pay the Rent 1.m4a
11 My Baby's Got To Pay the Rent 1.txt
11 Summertime Sadness 1.m4a
11 The Troubles 1.m4a
12 Canoeing (Katie and Alex's Theme) 1.m4a
6 Habits (Stay High) [Hippie Sabotage Remix] 1.txt
Tin's file.txt
hello
pwd


# Show's that find looks different than ls and you want to keep that in mind,
find . -print0 | xargs -0 -I{} echo {}
.
./11 My Baby's Got To Pay the Rent 1.m4a
./11 My Baby's Got To Pay the Rent 1.txt
./11 Summertime Sadness 1.m4a
./11 The Troubles 1.m4a
./12 Canoeing (Katie and Alex's Theme) 1.m4a
./6 Habits (Stay High) [Hippie Sabotage Remix] 1.txt
./hello
./pwd
./Tin's file.txt

 

 

Useful Applications of xargs

Search - ...

find . -print0 | xargs -0 -I{} echo {}