gpt4 book ai didi

powershell - 从字符串行中删除空格并将其用于数组

转载 作者:行者123 更新时间:2023-12-01 08:35:01 32 4
gpt4 key购买 nike

我正在浏览旧帖子,但我找不到非常具体的答案如何替换字符串中的空格,然后将其用作数组。

输入文件包含以下行:

-rw-r--r--   1 myuser admin   315279199 May 12 02:46 2016_05_12_backup.tar.gz
-rw-r--r-- 1 myuser admin 315278122 May 13 04:56 2016_05_13_backup.tar.gz

我想收到以下输出:

program executed on 2016-05-16 / 12:18:06
to unix:
rm -fr 2016_05_12_backup.tar.gz
rm -fr 2016_05_13_backup.tar.gz


to excel log:
2016_05_12_backup.tar.gz
2016_05_13_backup.tar.gz

=============== END ==============

我的代码在这里:

$path_in = "C:\test\input.txt"
$path_out = "C:\test\output.txt"

$endMessage = "=============== END =============="

$reader = [System.IO.File]::OpenText($path_in)
$get_time_message = "program executed on " + [datetime]::now.ToString('yyyy-MM-dd / HH:mm:ss')

try {

add-content $path_out $get_time_message
add-content $path_out "to unix: "

$long_string_to_excel =""


while($true){
$line = $reader.ReadLine()

if ($line -eq $null) { break }

# divide the input line into array - remove white space
# it is hard coded here below for the lines that consist two and three space characters

$better_line = $line.replace(' ',' ')
$best_line = $better_line.replace(' ',' ').split(' ')

$stringToOutput = "rm -fr " + $best_line[8]

$long_string_to_excel = $long_string_to_excel + $best_line[8] + "`r`n"

add-content $path_out $stringToOutput

}

add-content $path_out "`n"
add-content $path_out "to excel log: "
add-content $path_out $long_string_to_excel
add-content $path_out $endMessage

}
finally {
$reader.Close()
}
write-host "program execution:`ncompleted"

此脚本工作正常,但它是针对包含两个和三个空格字符的输入行进行“硬”编码的。我想用

    $better_line =  $line.replace(' +', ' ');
$best_line = $better_line.split(' ')

代替

    $better_line =  $line.replace('   ',' ')
$best_line = $better_line.replace(' ',' ').split(' ')

但结果不正确:

program executed on 2016-05-16 / 12:18:04
to unix:
rm -fr 315279199
rm -fr 315278122


to excel log:
315279199
315278122

=============== END ==============

您能否建议解决方案如何替换硬编码部分,以便脚本适用于单行中的任何类型的空白?

最佳答案

使用内置的 -split operator 代替静态 String.Split() 方法- 它支持正则表达式,因此您可以使用它按“1 个或多个空格”进行拆分,例如:

PS C:\> "a   b" -split '\s+'
a
b
PS C:\> "a b" -split '\s+'
a
b

关于powershell - 从字符串行中删除空格并将其用于数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37258922/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com