¿Cómo concateno dos archivos de texto en PowerShell?


Estoy tratando de replicar la funcionalidad del comando "cat" en Unix.

Me gustaría evitar soluciones donde leo explícitamente ambos archivos en variables, concateno las variables juntas y luego escribo la variable concatenada.

Author: merlin2011, 2012-01-06

10 answers

Simplemente puede usar cat example1.txt, example2.txt | sc examples.txt. Seguramente también puede concatenar más de dos archivos con este estilo. Además, si los archivos tienen un nombre similar, puede usar:

cat example*.txt | sc allexamples.txt

El cat es un alias para Get-Content, y sc es un alias para Set-Content.

Nota 1 : Tenga cuidado con el último método : si intenta generar una salida a examples.txt (o similar que coincida con el patrón), ¡PowerShell entrará en un bucle infinito! (Acabo de probar esto).

Nota 2 : La salida a un archivo con > no conserva la codificación de caracteres! Esta es la razón por el uso Set-Content (sc) se recomienda.

 93
Author: Smi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-15 14:59:21

No usar cat... >; estropea la codificación de caracteres. Uso:

Get-Content files.* | Set-Content newfile.file

Me llevó horas descubrir esto.

 48
Author: user2074686,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-09 21:39:43

En cmd, puedes hacer esto:

copy one.txt+two.txt+three.txt four.txt

En PowerShell esto sería:

cmd /c copy one.txt+two.txt+three.txt four.txt

Mientras que la forma de PowerShell sería usar gc, lo anterior será bastante rápido, especialmente para archivos grandes. Y también se puede usar en archivos no-ASCII usando el interruptor /B.

 11
Author: manojlds,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-22 17:35:20

Puede usar el cmdlet Add-Content. Tal vez es un poco más rápido que las otras soluciones, porque no recupero el contenido del primer archivo.

gc .\file2.txt| Add-Content -Path .\file1.txt
 10
Author: mjsr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-27 13:14:36

Para concat archivos en símbolo del sistema sería

type file1.txt file2.txt file3.txt > files.txt

Powershell convierte el comando type en Get-Content, lo que significa que se producirá un error al usar el comando type en powershell porque el comando Get-Content requiere una coma que separe los archivos. El mismo comando en powershell sería

Get-Content file1.txt,file2.txt,file3.txt | Set-Content files.txt

 4
Author: Brian Kimball,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-03 15:52:55

He utilizado:

Get-Content c:\FileToAppend_*.log | Out-File -FilePath C:\DestinationFile.log 
-Encoding ASCII -Append

Esta multa adjunta. Agregué la codificación ASCII para eliminar los caracteres nul que Notepad++ mostraba sin la codificación explícita.

 3
Author: Phoenix14830,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-18 18:47:23

Si necesita ordenar los archivos por parámetro específico (por ejemplo, fecha y hora):

gci *.log | sort LastWriteTime | % {$(Get-Content $_)} | Set-Content result.log
 2
Author: Roman O,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-12 11:14:49

, puedes hacer algo como:

get-content input_file1 > output_file
get-content input_file2 >> output_file

Donde > es un alias para "out-file", y >> es un alias para "out-file-append".

 1
Author: vlad-ardelean,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-22 17:33:46

Dado que la mayoría de las otras respuestas a menudo obtienen el formato incorrecto (debido a la tubería), lo más seguro es lo siguiente:

add-content $YourMasterFile -value (get-content $SomeAdditionalFile)

Sé que quería evitar leer el contenido de Som SomeAdditionalFile en una variable, pero para guardar, por ejemplo, su formato de nueva línea no creo que haya una manera adecuada de hacerlo sin.

Una solución sería recorrer suile SomeAdditionalFile línea por línea y canalizarlo a suile YourMasterFile. Sin embargo, esto es demasiado uso intensivo de recursos.

 1
Author: Kamaradski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-02 11:18:03

Creo que el "modo powershell" podría ser:

set-content destination.log -value (get-content c:\FileToAppend_*.log )
 0
Author: dvjz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-03 08:18:02