Shell xargs – How to Make xargs Handle Spaces and Special Characters

shellwhitespacexargs

I have a file that contains a list of names. i.e.:

Long Name One (001)
Long Name Two (201)
Long Name Three (123)
...

with spaces and some special characters. I wanted to make directories out of these names, i.e.:

cat file | xargs -l1 mkdir

It makes individual directories separated by spaces, i.e. Long, Name, One, Two, Three, instead of Long Name One (001), Long Name Two (201), Long Name Three (123).

How can I do that?

Best Answer

Use -d '\n' with your xargs command:

cat file | xargs -d '\n' -l1 mkdir

From manpage:

-d delim
              Input  items  are  terminated  by the specified character.  Quotes and backslash are not special; every
              character in the input is taken literally.  Disables the end-of-file string, which is treated like  any
              other  argument.   This can be used when the input consists of simply newline-separated items, although
              it is almost always better to design your program to use --null where this is possible.  The  specified
              delimiter  may be a single character, a C-style character escape such as \n, or an octal or hexadecimal
              escape code.  Octal and hexadecimal escape codes are understood as for the printf command.    Multibyte
              characters are not supported.

Example output:

$ ls
file

$ cat file
Long Name One (001)
Long Name Two (201)
Long Name Three (123)

$ cat file | xargs -d '\n' -l1 mkdir

$ ls -1
file
Long Name One (001)
Long Name Three (123)
Long Name Two (201)
Related Question