【问题标题】:equivalent sed command for deleting rows in CSV file用于删除 CSV 文件中的行的等效 sed 命令
【发布时间】:2014-02-11 15:02:02
【问题描述】:

感谢任何帮助,如果我的术语不正确,请见谅。

find ./ -iname '*.csv' -exec sed -i '1,6d;$ d' '{}' ';'

这个在 cygwin 上运行的 unix 命令将遍历目录和以 .csv 结尾的子目录中的所有文件
对于每个文件,它会删除前 6 行和最后一行,这就是返回的文件。

我的问题是如何在 vbs 脚本中编写等效项?

我尝试编辑这样的内容 (taken from here) 以满足我的要求,但没有任何乐趣。

Set fso = CreateObject("Scripting.FileSystemObject")
Set csv = fso.OpenTextFile(WScript.Arguments(...))

If Not csv.AtEndOfStream Then csv.SkipLine  'skip first row

Do Until csv.AtEndOfStream
  line = csv.ReadLine
  'process read line
Loop

csv.Close

注意:然后我想使用任务调度程序定期安排这个 vbs 脚本

编辑 在运行脚本之前,该文件将如下所示:(row7 和 row?? 之间的行数是可变的且未知的)

<blank line/row1>
<blank line/row2>
<Text would be on this row/line3>
<Text would be on this row/line4>
<Text would be on this row/line5>
<blank line/row6>
<Text would be on this row/line7>
.
.
.
<Text would be on this row/line??>
<Text would be on this Last row/line>

【问题讨论】:

  • +1 尝试解决您的问题。但是……sed和vbs对文本处理的操作模型,共同点很少。考虑编辑您的问题以包含示例数据,进一步示例显示每个 sed 命令在该文本中发生的转换。一些vbs 程序员可能理解sed 命令,但更多人会理解并举例说明我有这个数据X,我需要将它转换为Y。祝你好运。

标签: csv vbscript sed


【解决方案1】:
dim fso, csv, Iter, ThisLine

Set fso = CreateObject("Scripting.FileSystemObject")
Set csv = fso.OpenTextFile(WScript.Arguments(...))

Iter=1
while not csv.AtEndOfStream 
   ' Buffer the line for last line test
   ThisLine = csv.ReadLine

   ' stdout if after the 6th line and not the last (the one EOF is true after reading the line)
   if (Iter > 6) and ( not csv.AtEndOfStream) then
      wscript.echo ThisLine
    end if
   Iter = Iter + 1
 wend

csv.Close

如果约束是 X 最后一行而不是最后一行,您应该首先读取文件,计算行数而不是使用此对象(流文本文件)评估行号。 否则,如果不是太大,则在内存中加载 X 行的缓冲区或使用其他方法读取文件(以 ADO 为例,您有一个光标的概念来知道行的绝对位置和最后一行号)

【讨论】:

  • tks 这看起来像是一个起点。我只需要弄清楚如何将其写入文件。
【解决方案2】:

我会这样做:

Set fso = CreateObject("Scripting.FileSystemObject")

filename = "C:\path\to\your.csv"

Set inFile  = fso.OpenTextFile(filename)
Set outFile = fso.OpenTextFile(filename & ".tmp", 2, True)

Do Until inFile.AtEndOfStream
  If inFile.Line <= 6 Then
    inFile.SkipLine
  Else
    if Not IsEmpty(line) Then outFile.WriteLine line
    line = inFile.ReadLine
  End If
Loop

inFile.Close
outFile.Close

fso.DeleteFile filename, True
fso.MoveFile filename & ".tmp", filename

这里的技巧是在读取当前行之前打印上一次迭代的行。这样最后一行就省略了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-07
    • 1970-01-01
    • 2010-09-10
    • 1970-01-01
    • 2012-05-11
    • 2020-07-01
    • 2020-08-04
    相关资源
    最近更新 更多