PowerShell提取方括号之间的数字并插入到以下行中

i2loujxw  于 2023-03-02  发布在  Shell
关注(0)|答案(1)|浏览(137)

我正在尝试插入从前一行提取的项目编号。我有一个文件,其中的文本组在方括号中编号。
例如

some text

line 1: [1]
line 2: id = Item 

line 1: [2]
line 2: id = Item

应改为:
x一个一个一个一个x一个一个二个x

gojuced7

gojuced71#

例如,带有-Regex标志的switch可用于此目的:

$content = @'
some text

line 1: [1]
line 2: id = Item

line 1: [2]
line 2: id = Item

line 1: [123]
line 2: id = Item
'@ -split '\r?\n'

switch -Regex ($content) {
    '(?<=\[)[^\]]+' {
        # capture whats between brackets
        $value = $Matches[0]
        # output the line
        $_
        # go to next line
        continue
    }
    # if there was a capture previously
    { $value } {
        # replace the end of the line including
        # any possible whitespaces before it
        # with a space and the captured value
        $_ -replace '\s*$', " $value"
        # reset the value
        $value = $null
        # go to next line
        continue
    }
    # output this line if none of the above
    Default { $_ }
}

如果你正在阅读一个文件,你可以使用-File参数,逻辑仍然是一样的:

# this outer scriptblock allows us to pipe the output
# from the switch to Set-Content
& {
    switch -Regex -File $filepath {
        # same logic here
    }
} | Set-Content path\to\resultfile.ext

相关问题