2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

空行のインデントを前後の行とそろえる(PowerShell版)

Last updated at Posted at 2014-01-08

あるテキストエディタにおいて、複数行をまとめてインデントしても空行がインデントされない仕様に変わったときに書いたスクリプト。
2年ほど前に書いたので内容はうろおぼえだけど、たぶんタブインデントにしか対応していない。

こういうテキストのインデントを、

1111\n
\n
  2222\n
    3333\n
      4444\n
    3333\n
\n
    3333\n
      4444\n
    3333\n
  \n
  2222\n
\n
1111\n

こういう風にそろえる。

1111\n
  \n
  2222\n
    3333\n
      4444\n
    3333\n
    \n
    3333\n
      4444\n
    3333\n
    \n
  2222\n
  \n
1111\n
IndentEmptyLine.ps1
# 空行のインデントをそろえる

# 対象の空行のインデントレベルが、前後の行と異なる場合、
# 前後の行のうち深いほうのインデントレベルにそろえる

param(
    [string]$sourceFilePath,
    [string]$targetFilePath
)

$enc = [Text.Encoding]::GetEncoding("Shift_JIS")
$writer = New-Object IO.StreamWriter($targetFilePath, $false, $enc)

$lines = get-content $sourceFilePath
$i = 0

$outLine = ""
$prevIndent = ""

foreach ($line in $lines) {
    
    $i++
    
    #空行のとき
    if ($line -match "^\t*$") {
        $emptyLineCount++
        
        #次行以降の空行でない行を取得する
        $n = $i
        $nextIndent=""
        while ($n++ -lt $lines.count) {
            if ($lines[$n] -match "^(?<indent>\t*)[^\t]+$") {
                $nextIndent = $matches["indent"]
                break
            }
        }
        
        #前後の行のうち深い方のインデントレベルを取得する
        if ($prevIndent.length -lt $nextIndent.length) {
            $indent = $nextIndent
        } else {
            $indent = $prevIndent
        }
        
        #$outLine = $indent + "|"
        $outLine = $indent
        $indentedLineCount++
        
    } else {
        $outLine = $line
    }
    
    #前行のインデントレベルとして取得しておく
    if ($line -match "^(?<indent>\t*)[^\t]+$") {
        $prevIndent = $matches["indent"]
    }
    
    #ファイルに出力する
    $writer.WriteLine($outLine)
    #$outLine
}

$indentedLineCount.tostring() + " / " + $emptyLineCount.tostring() + "行処理しました"

$writer.close()
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?