YourPalNurav
YourPalNurav

Reputation: 1320

How to create bulk empty files with incremental filenames in cmd/powershell?

If I want to create 10 empty .txt files with the name pattern abcd01.txt, abcd02.txt,... ,abcd10.txt. How can this be achieved in CMD/PowerShell?

This I what I did to achieve:

for($i = 0; $i -lt 11; $i++){ New-Item -Path "C:\Users\FOO\Desktop\FOOBAR\abcd",$i,".txt" -ItemType File }

This created the files without any file extension. 0, 1, 2,... , 10.

Then I renamed all files with:

 Dir -filter * | %{Rename-Item $_ -NewName ("abcd{0}.cpp" -f $nr++)}

Is there a one-line command to make 'n' empty file with certain '.xyz' extension?

Upvotes: 2

Views: 960

Answers (2)

Io-oI
Io-oI

Reputation: 2565


enter image description here


  • For the record! With you can do this by:

In command line:


for /l %N in (1 1 10)do @set "%N=0%N" && cmd /v /c "cd.>"c:\temp\test!%N:~-2!.txt""

:: or ::

for /l %N in (1 1 10)do @set "%N=0%N"&&cmd/v/c"cd.>"c:\temp\test!%N:~-2!.txt""


In cmd/bat file:


for /l %%N in (1 1 10)do set "%%N=0%%N" && cmd /v /c "cd.>"c:\temp\test!%%N:~-2!.txt""

:: or ::

for /l %%N in (1 1 10)do set "%%N=0%%N"&&cmd/v/c"cd.>"c:\temp\test!%%N:~-2!.txt""

Upvotes: 2

hcm
hcm

Reputation: 1020

You can format leading zeros in a variable which you use in new-item:

for($i = 1; $i -lt 11; $i++){
    $path = "C:\temp\test{0:00}.txt" -f $i
    New-Item -Path $path
}

And by the way, your new-item did not add any extensions because

New-Item -Path "C:\Users\FOO\Desktop\FOOBAR\abcd",$i,".txt"

should be

New-Item -Path "C:\Users\FOO\Desktop\FOOBAR\abcd$i.txt"


Also if you need to make 'n' copies of a file named 'xyz.txt', you can use the following:

for($i=1; $i -lt 11; $i++){
    $path = "C:\temp\foo\test{0:00}.txt" -f $i
    New-Item $path
    $cont = Get-Content "foo.txt"
    Set-Content $path $cont
}

Upvotes: 8

Related Questions