如何在 PowerShell 中连接两个文本文件? [英] How do I concatenate two text files in PowerShell?

查看:37
本文介绍了如何在 PowerShell 中连接两个文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Unix 中复制 cat 命令的功能.

I am trying to replicate the functionality of the cat command in Unix.

我想避免将两个文件显式读入变量,将变量连接在一起,然后写出连接变量的解决方案.

I would like to avoid solutions where I explicitly read both files into variables, concatenate the variables together, and then write out the concatenated variable.

推荐答案

只需使用 Get-ContentSet-Content cmdlet:

Simply use the Get-Content and Set-Content cmdlets:

Get-Content inputFile1.txt, inputFile2.txt | Set-Content joinedFile.txt

您也可以使用这种样式连接两个以上的文件.

You can concatenate more than two files with this style, too.

如果源文件名称相似,可以使用通配符:

If the source files are named similarly, you can use wildcards:

Get-Content inputFile*.txt | Set-Content joinedFile.txt

注意 1: PowerShell 5 和更早版本允许使用 Get 的别名 catsc 更简洁地完成此操作-ContentSet-Content 分别.但是,这些别名是有问题的,因为 cat 在 *nix 系统中是系统命令,而 sc 在 Windows 系统中是系统命令 - 因此不推荐使用它们,并且在事实上 sc 甚至不再定义为 PowerShell Core (v7).PowerShell 团队一般建议不要使用别名.

Note 1: PowerShell 5 and older versions allowed this to be done more concisely using the aliases cat and sc for Get-Content and Set-Content respectively. However, these aliases are problematic because cat is a system command in *nix systems, and sc is a system command in Windows systems - therefore using them is not recommended, and in fact sc is no longer even defined as of PowerShell Core (v7). The PowerShell team recommends against using aliases in general.

注意 2:小心通配符 - 如果您尝试输出到 examples.txt(或与模式匹配的类似内容),PowerShell 将进入无限循环!(我刚刚测试了这个.)

Note 2: Be careful with wildcards - if you try to output to examples.txt (or similar that matches the pattern), PowerShell will get into an infinite loop! (I just tested this.)

注意 3:输出到带有 > 的文件不会保留字符编码!这就是为什么推荐使用 Set-Content.

Note 3: Outputting to a file with > does not preserve character encoding! This is why using Set-Content is recommended.

这篇关于如何在 PowerShell 中连接两个文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆