简体   繁体   中英

Create empty multiple files in Unix that contain 0 bytes using awk or bash?

I am trying to create multiple empty files on Unix but I do not know if AWK command can do that or do I have to do it in bash? if yes could you help me, please?

At this moment I use this command:

seq 2 | awk '{print "" > "empty"i++".txt"}' i=1

however every file that is created is 1 byte. Is there a way to create 0 byte file using awk or bash?

How about:

touch $(seq 2)

or:

touch $(seq 2 | sed 's/$/.txt/')

if you want a suffix?

The touch command will create a file if it doesn't exist. So you could do:

for i in `seq 1 2`; do
    touch empty$i.txt
done

If you don't want to use any other commands like touch , and do it purely using bash commands, you could use the redirection operator > without a command in front of it:

for i in `seq 1 2`; do
    > empty$i.txt
done

For more details see the I/O Redirection chapter in the Advanced Bash-Scripting Guide :

> filename    
   # The > truncates file "filename" to zero length.
   # If file not present, creates zero-length file (same effect as 'touch').
   # (Same result as ": >", above, but this does not work with some shells.)

If you really want to do it in awk :

seq 2 | awk '{system(">" "empty" FNR ".txt")}'

That's not very clever though because it creates a whole new process for every line that awk reads.

@EdMorton's suggestion is therefore preferable, as he uses awk 's internal printf rather than creating a separate process:

seq 2 | awk '{printf "" > "empty" NR ".txt"}'

You would be better to use this:

touch {1..2}.txt

which only creates one process. However, that will not reduce to zero the size of any pre-existing files you may have - I don't generally like to assume folk are happy to lose data unless they explicitly say so in their question.

The awk command can indeed create empty files on its own, without spawning something in system() :

$ awk 'BEGIN{ printf("") > "test1" }'
$ ls -l test1
-rw-r--r--  1 ghoti  staff  0 Jan  9 09:58 test1
$

Note that each output file is recorded in memory upon use, and that memory is not given back until the output file is closed. You can use the close() function to close a file.

awk -v n=2 'BEGIN{ for(;n;n--) { f="test"n".txt"; printf("") > f; close(f) } }'

But you by no means need awk for this, the touch works nicely from multiple shells (including bash of course), and the mechanism you use to generate filenames for it are numerous and varied.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM