Khaled Ismail
Khaled Ismail

Reputation: 315

"Cat" into multiple files using brace expansion

I am quite new to bash and trying to type some text into multiple files with a single command using brace expansion.

I tried: cat > file_{1..100} to write into 100 files some text that I will type in the terminal. I get the following error:

bash: file_{1..100}: ambiguous redirect

I also tried: cat > "file_{1..100}" but that creates a singe file named: file_{1..100}.

I tried: cat > `file_{1..100}` but that gives the error: file_1: command not found

How can I achieve this using brace expansion? Maybe there are other ways using other utilities and/or pipelines. But I want to know if that is possible using only simple brace expansion or not.

Upvotes: 0

Views: 735

Answers (3)

kruz
kruz

Reputation: 31

This types the string or text into file{1..4}

echo "hello you just knew me by kruz" > file{1..4}

Use to remove them

rm file*

Upvotes: -1

Nate Eldredge
Nate Eldredge

Reputation: 58007

You can't do this with cat alone. It only writes its output to its standard output, and that single file descriptor can only be associated with a single file.

You can however do it with tee file_{1..100}.

You may wish to consider using tee file_{01..100} instead, so that the filenames are zero-padded to all have the same width: file_001, file_002, ... This has the advantage that lexicographic order will agree with numerical order, and so ls, *, etc, will process them in numerical order. Without this, you have the situation that file_2 comes after file_10 in lexicographic order.

Upvotes: 4

Saboteur
Saboteur

Reputation: 1428

target could be only a pipe, not a multiple files. If you want redirect output to multiple files, use tee

cat | tee file_{1..100}

Don't forget to check man tee, for example if you want to append to the files, you should add -a option (tee -a file_{1..100})

Upvotes: 3

Related Questions