如何让 xargs 处理来自 cat 的空格和特殊字符?

Maj*_*jal 13 shell xargs whitespace

我有一个file包含名称列表的列表。IE:

Long Name One (001)
Long Name Two (201)
Long Name Three (123)
...
Run Code Online (Sandbox Code Playgroud)

带有空格和一些特殊字符。我想用这些名称创建目录,即:

cat file | xargs -l1 mkdir
Run Code Online (Sandbox Code Playgroud)

它使各个目录以空格分隔,即Long, Name, One, Two, Three, 而不是 Long Name One (001), Long Name Two (201), Long Name Three (123)

我怎样才能做到这一点?

Pan*_*dya 16

-d '\n'与您的xargs命令一起使用:

cat file | xargs -d '\n' -l1 mkdir
Run Code Online (Sandbox Code Playgroud)

从联机帮助页:

-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.
Run Code Online (Sandbox Code Playgroud)

示例输出:

$ 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)
Run Code Online (Sandbox Code Playgroud)


cuo*_*glm 8

如果您的 xargs 实现支持-0选项:

tr '\n' '\0' <file | xargs -0 -l1 mkdir
Run Code Online (Sandbox Code Playgroud)

POSIXly:

while IFS= read -r file; do
  mkdir -p -- "$file"
done <file
Run Code Online (Sandbox Code Playgroud)

(请注意,while在 shell 脚本中使用循环处理文本被认为是不好的做法)