Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell 提取由特定字符分隔的两个字符串_Powershell - Fatal编程技术网

Powershell 提取由特定字符分隔的两个字符串

Powershell 提取由特定字符分隔的两个字符串,powershell,Powershell,我是Powershell的新手,我必须解决一个问题。我一直在寻找不同的解决方案,但我不知道如何继续。。。从文本文件中,我必须: 提取由“|”分隔的两个字符串 验证两个字符串是否相同 如果是,那么,我在txt文件中导出结果,只保留string1 如果不是,我将结果导出到txt文件中作为string2.string1 例如,我的文件如下所示: column name toulon|1|0|||||||wan|toulon lille-test|1|0|||||||wan|Lille 预期输出是一个

我是Powershell的新手,我必须解决一个问题。我一直在寻找不同的解决方案,但我不知道如何继续。。。从文本文件中,我必须:

  • 提取由
    “|”
    分隔的两个字符串
  • 验证两个字符串是否相同
  • 如果是,那么,我在txt文件中导出结果,只保留string1
  • 如果不是,我将结果导出到txt文件中作为string2.string1
  • 例如,我的文件如下所示:

    column name
    toulon|1|0|||||||wan|toulon
    lille-test|1|0|||||||wan|Lille
    
    预期输出是一个txt文件,包含:

    toulon
    lille.lille-test
    

    如果需要,我可以提供源文件和预期输出。

    一种方法是使用
    -Split
    操作符根据
    |
    字符进行定界,执行字符串比较,然后使用
    -join
    操作符连接结果

    $Lines = Get-Content -Path "test.txt"
    $lines | Foreach-Object {
        $splits = $_  -Split "\|"
        if ($splits[0] -eq $splits[-1]) {
            $splits[0]
        }
        else {
            $splits[-1,0] -Join "."
        }
    }
    

    到目前为止,您尝试了什么?您遇到了哪些具体错误?我们不仅仅是为你写东西,我们还帮助人们解决具体问题。此外,您的问题没有多大意义,因为每个示例中都有多个字符串……请显示所有三行-看起来您有一个CSV文件,其分隔符设置为
    另外,您将
    lille.lille test
    显示为第2行的输出。。。这不在第二行。[咧嘴笑]所以。。。请发布源代码和预期输出。太棒了!这正是我所期望的。只需将此输出发送到txt文件。谢谢