[英]Powershell script to replace only the tab characters in substrings enclosed in double quotes
I'm working with a tab separated values (tsv) text file.我正在使用制表符分隔值 (tsv) 文本文件。 I'm importing it into Excel but for some reason it is also treating tab chars in strings (denoted with double quotes) as delimiters.
我正在将它导入 Excel,但出于某种原因,它还将字符串中的制表符(用双引号表示)视为分隔符。
A line in the file looks like this:文件中的一行如下所示:
Name Quote Random text
Harry "I like putting tabs in sentences" "Here is another tab "
I'm trying to write a powershell script to read the whole text file, find only tab chars enclosed in quotes and replace them with a space character.我正在尝试编写一个 powershell 脚本来读取整个文本文件,只找到用引号括起来的制表符并将它们替换为空格字符。 I know this will be possible but the issue is I'm not an expert in Powershell or regex :D
我知道这是可能的,但问题是我不是 Powershell 或正则表达式的专家:D
Any ideas?有任何想法吗?
Try this -尝试这个 -
(Get-Content \\PathToYourTextFile\TabFile.txt).Replace("`t", " ")
OR或者
Get-Content \\PathToYourTextFile\TabFile.txt | % {$_ -replace ("`t", " ")}
Both will replace the tabs
in your text file to single spaces.两者都会将文本文件中的
tabs
替换为单个空格。
If you want to completely replace tabs with spaces, use solution provided by Vivek Kumar Singh .如果您想用空格完全替换制表符,请使用Vivek Kumar Singh提供的解决方案。
However, if you want to keep it as TSV you can import it to variable, replace tabs with space (in values only) and then export:但是,如果您想将其保留为 TSV,您可以将其导入变量,用空格替换制表符(仅限值),然后导出:
$content = Import-Csv .\file.tsv -Delimiter "`t"
foreach ($line in $content) {
$line.Name = $line.Name.replace("`t", " ")
$line.Quote = $line.Quote.replace("`t", " ")
$line.'Random text' = $line.'Random text'.replace("`t", " ")
}
$content | Export-Csv .\output.tsv -Delimiter "`t" -NoTypeInformation
By the way, this might not be needed as I for me Excel imports data correctly.顺便说一下,这可能不需要,因为我对我来说 Excel 可以正确导入数据。 Maybe some issue with the file/particular line?
也许文件/特定行有问题?
在替换命令中使用引号和水平制表符的十六进制值
(gc "\\Path to Your\file") -replace "[\x22][\x09][\x22]"," " | set-content "\\Path to Your\file"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.