[Linux]lsで取得したファイル一覧をTSV形式に変換して表計算ソフトに取り込みました

未分類
この記事は約5分で読めます。

 lsコマンドでファイルの一覧を取得できますが、表計算ソフトに貼り付けられるようなテーブルではありません。使い勝手を良くするためにCSVまたはTSV形式のファイルに変換してみましょう。

 lsコマンドの結果は次のような規則があります。
 「/」で始まる行はディレクトリをあらわします。ここからディレクトリの情報が表示されるという意味です。
 「-(ハイフン)」で始まる行はファイルです。

 では、ノーツ(開発プラットホーム)のアクションボタンでCSVやTSVに変換するプログラムをコーディングしてみましょう。
 ※最初はC#で変換しようとしましたが、ノーツの手軽さに負けました。

 次は、Windows OS のドキュメントフォルダの source.txt ファイルを読み込んで result.tsv を作成するプログラムになります。コーディングの手間を減らすためにファイル名を固定にしています。

Option Declare

Const SOURCE_FILE = {source.txt}
Const CHAR_SET = {UTF-8}
Const RESULT_FILE = {result.tsv}
Const PathPartition0 = {/}   ' 初期値
Const PathPartition1 = {\}   ' 選択値

Sub Click(Source As Button)
	Dim RESULT_SEPARATOR As String
	RESULT_SEPARATOR = Chr (9)
	
	Dim sourcefolder As String
	Dim pathpartition As String
	Dim sourcefilepath, resultfilepath As String
	Dim scriptshell As Variant
	Dim sourcefile, resultfile As Integer
	
	On Error Resume Next
	Set scriptshell = CreateObject ({WScript.Shell})
	sourcefolder = scriptshell.SpecialFolders ({MyDocuments})
	On Error Goto 0
	If 0 = Len (sourcefolder) Then
		Print {MyDocuments フォルダが不明}
		Exit Sub
	End If
	pathpartition = PathPartition0
	If 0 < Instr (1, sourcefolder, PathPartition1) Then
		pathpartition = PathPartition1
	End If
	sourcefilepath = sourcefolder + pathpartition + SOURCE_FILE
	
	
	sourcefile = Freefile ()
	Err = 0
	On Error Resume Next
	Open sourcefilepath For Input As sourcefile Charset = CHAR_SET
	On Error Goto 0
	If 0 < Err Then
		Print {ファイルが見つかりません : } + sourcefilepath
		Exit Sub
	End If
	resultfile = Freefile ()
	resultfilepath = sourcefolder + pathpartition + RESULT_FILE
	On Error Resume Next
	Open resultfilepath For Output As resultfile
	On Error Goto 0
	If 0 < Err Then
		Print {ファイルを作成できません : } + resultfilepath
		Close sourcefile
		Exit Sub
	End If
	
	Dim sourceline, currentdirectory As String
	currentdirectory = {}
	Do Until True = Eof (sourcefile)
		Line Input #sourcefile, sourceline
		Select Case Left (sourceline, 1)
		Case {/}
			Select Case Right (sourceline, 1)
			Case {:}
				currentdirectory = Left (sourceline, Len (sourceline) -1)
			End Select
		Case {-}
			Dim columns (1) As String
			Dim position, beforeposition, column As Long
			columns (0) = currentdirectory
			beforeposition = -1
			column = 1
			For position = 1 To Len (sourceline)
				Select Case Mid (sourceline, position, 1)
				Case { }
					If (beforeposition + 1) <> position Then
						column = column + 1
					End If
					beforeposition = position
				Case Else
					If (beforeposition + 1) = position Then
						If 8 = column Then
							columns (1) = Mid (sourceline, position)
							Exit For
						End If
					End If
				End Select
			Next
			Print #resultfile, Implode (columns, RESULT_SEPARATOR)
		End Select
	Loop
	Close resultfile
	Close sourcefile
End Sub

  表計算ソフトを開いて、メニューの[開く]から result.tsv を選択して、区切文字をタブに指定して読み込めば完了です。
 ls で / 以下すべてを取得しているとき、result.tsv の中身を表計算ソフトへコピペするとメモリ不足エラーが表示されることがあるため注意です。

タイトルとURLをコピーしました