【问题标题】:Search and replace the first delimiter in each line for large file?搜索并替换大文件每行中的第一个分隔符?
【发布时间】:2014-03-04 00:01:32
【问题描述】:

我有一些大文件(大于 2GB ),文件中的文本格式如下:

2013/4/18;22:5:42.668;13266;10;13279;10
2013/4/18;22:10:48.820;13271;10;13279;10
2013/4/18;22:12:0.956;13266;10;13279;10
2013/4/18;22:12:44.826;13266;10;13284;10
...

我想完成以下任务

- replace the 1st semi-colon ";" in each line to space character " "
- replace the rest semi-colon ";" in each line to comma character ","

输出应该如下所示

2013/4/18 22:5:42.668,13266,10,13279,10
2013/4/18 22:10:48.820,13271,10,13279,10
2013/4/18 22:12:0.956,13266,10,13279,10
2013/4/18 22:12:44.826,13266,10,13284,10
...

谁能告诉我怎么做?

【问题讨论】:

  • 你有emacs吗?在emacs中很容易
  • sed -e 's/;/ /' -e 's/;/,/g' 如果你有sed
  • @JonathanLeffler windows有sed吗?
  • @Nullpointer 我刚下载了emac,你能告诉我怎么做吗
  • @Nullpointer:Windows 上的 Cygwin 可以; MinGW 也是如此。但它们在 Windows 上不是标准的,因此我的评论中的“如果”(以及它的评论状态,而不是回答状态)。如果你有一个 Unix 派生的编辑器,那么你可以在文件上全局使用两个替换命令(例如,vim 中的:g/;/s/;/ /:g/;/s/;/,/g;在emacs 中也可以使用,但我不知道语法)。我不知道您如何仅使用 Windows 工具巧妙地做到这一点;可能有办法,但是...

标签: regex windows text


【解决方案1】:

虽然这不是一个正则表达式,但它会完成你的工作! 这叫emacs键盘宏!

这些是您在 emacs 中打开此文件后需要按的键。

为什么我要求您定义宏是因为一旦定义,您只需按一两个键即可随时对任何文件使用它。

在 emacs 中打开您的文件并开始按以下键:

alt-shift-, //go to the start of the file
ctrl-x-(    //start defining keyboard macro
ctrl-s      //search for some thing
;           //that something is your ;
ctrl-b      //move one step back
ctrl-d      //delete the ;
[space-bar] //add space
ctrl-[space-bar] //start selecting region
ctrl-e      //select region till the end of line
alt-shift-5 //replace all from region
;           //replace ; 
,           //with ,
shift-1     //do this for all ; in region
ctrl-e      //move to end of line
ctrl-f      //go to start of next line
ctrl-x-)    //end macro
//now-your-macro-is-defined
ctrl-[space-bar] //again define the region
alt-shift-.     //select all file (except first line)
M-x-apply-macro-to-region //apply perviously defined macro to complete file!

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    gVim for Windows 中可以轻松完成。首先,我们用简单的macro 将每行中的第一个分号替换为空格。要输入宏,请键入:

    ggq1(or any letter)^f;r jq 
    

    解释:

    • gg: 转到文件开头
    • q1:开始录制到注册1或任何地方
    • ^: 转到行首
    • f;:将;的出现转到右边
    • r:将光标下的字符替换为空格
    • j: 转到下一行
    • q:停止录音

    然后在命令模式下键入:2,$:normal @1 从第二行开始执行宏,现在所有行的第一个分号都被替换为空格。之后,使用:%s/;/,/g 替换其余的分号。

    【讨论】:

      【解决方案3】:

      这是一个可以完成这项工作的 perl one 班轮:

      perl -api.back -e 's/;/ /; s/;/,/g;' in.txt
      

      原文件保存在in.txt.back下,替换就地完成。

      【讨论】:

        猜你喜欢
        • 2013-01-08
        • 2021-06-12
        • 1970-01-01
        • 1970-01-01
        • 2015-03-28
        • 1970-01-01
        • 1970-01-01
        • 2018-07-30
        • 2011-07-17
        相关资源
        最近更新 更多