簡體   English   中英

Powershell 腳本僅替換雙引號括起來的子字符串中的制表符

[英]Powershell script to replace only the tab characters in substrings enclosed in double quotes

我正在使用制表符分隔值 (tsv) 文本文件。 我正在將它導入 Excel,但出於某種原因,它還將字符串中的制表符(用雙引號表示)視為分隔符。

文件中的一行如下所示:

Name  Quote  Random text
Harry  "I like putting    tabs in sentences"  "Here is another tab   "

我正在嘗試編寫一個 powershell 腳本來讀取整個文本文件,只找到用引號括起來的制表符並將它們替換為空格字符。 我知道這是可能的,但問題是我不是 Powershell 或正則表達式的專家:D

有任何想法嗎?

嘗試這個 -

(Get-Content \\PathToYourTextFile\TabFile.txt).Replace("`t", " ")

或者

Get-Content \\PathToYourTextFile\TabFile.txt | % {$_ -replace ("`t", " ")}

兩者都會將文本文件中的tabs替換為單個空格。

如果您想用空格完全替換制表符,請使用Vivek Kumar Singh提供的解決方案。

但是,如果您想將其保留為 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

順便說一下,這可能不需要,因為我對我來說 Excel 可以正確導入數據。 也許文件/特定行有問題?

在替換命令中使用引號和水平制表符的十六進制值

(gc "\\Path to Your\file") -replace "[\x22][\x09][\x22]"," " | set-content "\\Path to Your\file"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM