Strange grammar in cat command

这一生的挚爱 提交于 2019-12-22 10:39:41

问题


First of all, I apologize if this question can be answered with a web search, but I couldn't find anything.

There is some grammar in the cat command which I've seen to "repeat" files.

cat file{,}

Is equivalent to calling

cat file file

Also,

cat file{,}{,}{,}{,}

repeats file not four times, but 16 times. In addition,

cat file{,,}

repeats file 3 times.

I would like to know more about this grammar. What is it called? Is it built into cat or is it a shell feature? Are there more features of this grammar?


回答1:


This feature is called brace expansion.

Generally you can write file{1,2,3} and bash expands it to file1 file2 file3 before running the command.

If you write

mkdir foo{1,2,3}{a,b}

it will be equivalent to

mkdir foo1a foo1b foo2a foo2b foo3a foo3b

and will create those 6 directories.

In your case ({,}) you are adding nothing and nothing and therefore get the same word twice.




回答2:


The syntax that you are referring to is known as brace expansion.

The {,,} syntax is often used to repeat words. Saying:

echo foo{,,}

would produce

foo foo foo

When you combine brace expansions, it's equivalent to nesting those:

echo foo{,}{,}{,}

is equivalent to saying

echo foo\ foo{,}{,}

and to

echo foo\ foo\ foo\ foo{,}

and produces

foo foo foo foo foo foo foo foo

Essentially, n pairs of {,} after a given string would generate the string 2n times.

In addition to link mentioned above, you can also learn about brace expansion here.



来源:https://stackoverflow.com/questions/22434207/strange-grammar-in-cat-command

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!