提取特定行并导出到另一个 txt 文件 [英] Extracting specific lines and export to the another txt file

查看:44
本文介绍了提取特定行并导出到另一个 txt 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提取平面文件中的特定行,然后导出到另一个 txt 文件.

I want to extract specific lines inside flat file and then export to the another txt file.

最后,我想通过 write-host 添加信息消息.

Lastly , I want to add information message via write-host.

done. 2 Records have been extracted in "C:\tmp\output.txt"

我的输入文件:

MyComputer1234.child1 [AGE:3606209] 1200 A 172.2.3.4

MyComputer5678 [AGE:1782367] 1200 A 172.5.6.7

MyComputer90AB.child2 [AGE:2457912] 1200 A 172.9.0.1

MyComputerCDEF.child2 [AGE:1982627] 1200 A 172.10.11.12

我的输出:

MyComputer90AB.child2 [AGE:2457912] 1200 A 172.9.0.1
MyComputerCDEF.child2 [AGE:1982627] 1200 A 172.10.11.12

脚本:

get-content $inputfile -ReadCount 1000 |
 foreach { $_ -match "child2" }

我想要的输出:

MyComputer90AB [AGE:2457912] 1200 A 172.9.0.1

MyComputerCDEF [AGE:1982627] 1200 A 172.10.11.12

推荐答案

您尚未执行任何操作来删除匹配的字符串部分.这可以通过正则表达式轻松实现.

You haven't done anything to remove that portion of the string that you matched. This is easily accomplished with regular expressions.

Get-Content $inputfile |
 ForEach-Object {
    if($_ -match "child2"){
        $_ -replace '\.child2'
    }
 }

由于句点 (.) 在正则表达式中具有特殊含义,因此您必须使用反斜杠将其转义.我还建议使用 switch 语句来读取和解析文件.

Since the period (.) has a special meaning in regex you have to escape it with the backslash. I'd also recommend using a switch statement to read and parse the file.

switch -Regex -File $inputfile {
    'child2' {$_ -replace '\.child2'}
}

编辑

基于您的输入文件示例.

Based on YOUR input file example.

$inputfile = New-TemporaryFile

@'
MyComputer1234.child1 [AGE:3606209] 1200 A 172.2.3.4

MyComputer5678 [AGE:1782367] 1200 A 172.5.6.7

MyComputer90AB.child2 [AGE:2457912] 1200 A 172.9.0.1

MyComputerCDEF.child2 [AGE:1982627] 1200 A 172.10.11.12
'@ | Set-Content $inputfile

我提出的第一个解决方案

My first proposed solution

Get-Content $inputfile |
    ForEach-Object {
    if($_ -match "child2"){
        $_ -replace '\.child2'
    }
}

输出

MyComputer90AB [AGE:2457912] 1200 A 172.9.0.1
MyComputerCDEF [AGE:1982627] 1200 A 172.10.11.12

我提出的第二个解决方案

My second proposed solution

switch -Regex -File $inputfile {
    'child2' {$_ -replace '\.child2'}
}

输出

MyComputer90AB [AGE:2457912] 1200 A 172.9.0.1
MyComputerCDEF [AGE:1982627] 1200 A 172.10.11.12

这篇关于提取特定行并导出到另一个 txt 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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