Home > Mobile >  Save all files content from a directory and sub directory into a single file with Windows cmd/Powers
Save all files content from a directory and sub directory into a single file with Windows cmd/Powers

Time:05-05

So, I have a folder with sub folders with files of different types (php,js,html). I would like to know if there is a command on windows powershell/cmd to save all files content of my directory into a single file. In brief, I would like to do a recursive cat > save.txt on windows. Thank you in advance

CodePudding user response:

Use Get-ChildItem to recursively discover any files in the folder hierarchy, then pipe those to Get-Content (for reading) and finally pipe the output from those calls to Set-Content (for writing the whole thing back to disk).

Get-ChildItem path\to\root\folder -Recurse -File |Get-Content |Set-Content path\to\save.txt

Note: Unlike cat, Get-Content reads the files as text/strings by default, so this will work well for text-encoded files (like js, php and html source files), but won't work on binary files

CodePudding user response:

From the command prompt:

You can use the copy command with the character to concatenate multiple files:

copy file1.txt file2.txt save.txt.

To concatenate all files in a directory use the for command in combination with dir /b (/b means bare format, only files names)

for /f %f in ('dir *.* /b') do @type %f>>save.txt

Or recursively, using /s for directory and all subdirectories in combination with /a:-d to exclude directories in the output.

for /f %f in ('dir *.* /b /s /a:-d') do @type %f>>save.txt

Using PowerShell:

Concatenate list of files:

Get-Content .\file1.txt,.\file2.txt | Out-File Save.txt

Concatenate all files in a directory:

(Get-ChildItem -File | ForEach-Object { Get-Content $_ } ) | out-file save.txt

Concatenate all files recursively:

(Get-ChildItem -File -Recurse | ForEach-Object { Get-Content $_.FullName } ) | out-file save.txt

Note: for binary files you may want to add the /b switch to the copy command or if using PowerShell add -Raw to Get-Content

  • Related