数组索引计算为null - 查找亚麻并将其用作索引号

问题描述 投票:0回答:1

我的输入文件如下所示:

#EXTM3U
#EXTI NF:-1 tvg-name="Das Erste HD" tvg-id="ARD.de" group-title="Vollprogramm" tvg-logo="https://raw.githubusercontent.com/jnk22/kodinerds-iptv/master/logos/tv/daserstehd.png",Das Erste HD
https://daserstehdde-lh.akamaihd.net/i/daserstehd_de@625196/index_2739_av-p.m3u8
#EXTINF:-1 tvg-name="Das Erste" tvg-id="ARD.de" group-title="Vollprogramm" tvg-logo="https://raw.githubusercontent.com/jnk22/kodinerds-iptv/master/logos/tv/daserste.png",Das Erste
https://daserstelive-lh.akamaihd.net/i/daserste_de@28289/index_3776_av-p.m3u8
..

我想用我的变量$newRtsp替换流并将其写回文件。我现在拥有的是:

# Getting the file
$inFile = Get-Content "iptv.m3u"

# Linenumber where a specific channel name $chanName exists
$line = ($inFile | Select-String "tvg-name=`"$chanName`"").LineNumber                                                                                          #`# dummy comment to fix code highlighting for SO

# Use actual Linenumber as Index, to override the following line
$inFile[$line] = $newRtsp

# Write back to file
$inFile | Set-Content "iptv.m3u"

问题:不知何故,我不能使用找到的亚麻布作为索引:

Index operation failed; the array index evaluated to null.
At E:\merge-fritzbox.ps1:17 char:5
+     $inFile[$line] = $newRtsp
+     ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArrayIndex
powershell
1个回答
1
投票

Select-String返回的行号从1开始计算。数组索引从0开始计算,因此您需要考虑这一点。

这应该工作:

$chanName = "Das Erste HD"
$newRtsp  = "the new content for the line"

# Getting the file
$inFile = Get-Content "iptv.m3u"

# Linenumber where a specific channel name $chanName perhaps exists?
# SimpleMatch is an optional parameter and specifies that 
# the string in the pattern is not interpreted as a regular expression.
$line = ($inFile | Select-String "tvg-name=`"$chanName`"" -SimpleMatch).LineNumber               #`# dummy comment to fix code highlighting for SO

# $line will be $null if Select-String did not find the string to look for
if ($line) {
    # Use actual Linenumber minus 1 as Index, to override the following line
    $inFile[$line - 1] = $newRtsp

    # Write back to file
    $inFile | Set-Content "iptv.m3u"
}
© www.soinside.com 2019 - 2024. All rights reserved.