我一直在浏览旧文章,但是找不到非常具体的答案,如何替换字符串中的空白然后将其用作数组。
输入文件包括以下几行:
-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 ==============
您能否在解决方案中提出建议,如何替换硬编码部分,以便脚本可在一行中用于任何类型的空白?
可以String.Split()
使用内置-split
运算符代替静态方法-它支持正则表达式,因此您可以使用它来分割“ 1个或多个空格”,例如:
PS C:\> "a b" -split '\s+'
a
b
PS C:\> "a b" -split '\s+'
a
b
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句