'Concatenating Files And Insert a Word In Between Files

I have around 3000 .gz files that I need to concatenate with the word "break" in between each file in PowerShell.

cat *gz > allmethods.txt

This concatenates all my files but does not leave any space in between. I need to add a word in between each file. Any help would be appreciated.



Solution 1:[1]

Try the following:

Get-Content -Raw *gz | 
  ForEach-Object { $_ + 'break' } |
    Set-Content -Encoding utf8 allmethods.txt
  • On Windows, cat is a built-in alias for the Get-Content cmdlet; -Raw reads each matching file in full, as a single, multiline string.

  • The ForEach-Object call concatenates each file's content, reflected in the automatic $_ variable variable with verbatim string break and outputs the result.

    • Note: This assumes that each input file has a trailing newline and that you don't want an empty line before each occurrence of break; to in effect insert a newline between the file's content and break, use $_; 'break' instead.

    • The last file's content will also be followed by break.

  • The Set-Content call saves all strings it receives to the specified output file, using the specified encoding via the -Encoding parameter - adjust as needed.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1