dpqg86714 2017-02-12 19:49
浏览 121
已采纳

使用sed将文件拆分为两个文件

I have a file of around 250M, which I want to split into two using the sed command in ubuntu.

The line from which I wan to split is like:

DROP TABLE IF EXISTS `captcha_log`CREATE TABLE IF NOT EXISTS `captcha_log`

The second file should include the above string.

  • 写回答

1条回答 默认 最新

  • dswm97353 2017-02-12 20:11
    关注

    You can use the csplit tool for this:

    pattern='DROP TABLE IF EXISTS `captcha_log`CREATE TABLE IF NOT EXISTS `captcha_log`'
    csplit infile /"$pattern"/
    

    If you really want to use sed, you could do it in two steps:

    pattern='DROP TABLE IF EXISTS `captcha_log`CREATE TABLE IF NOT EXISTS `captcha_log`'
    sed -n "/$pattern/q;p" infile > outfile1
    sed -n "/$pattern/,\$p" infile > outfile2
    

    -n prevents printing as the default action; /$pattern/q exits as soon as the pattern line is reached, and p is executed for each line before that.

    The second command just uses an address range, from the pattern line to the last one $. Because the command is double quoted to get $pattern in, the $ for the last line has to be escaped, \$.

    Or you could do a single pass with awk:

    pattern='DROP TABLE IF EXISTS `captcha_log`CREATE TABLE IF NOT EXISTS `captcha_log`'
    awk -v pattern="$pattern" '$0 == pattern { ++flag }
                               flag { print > "outfile2"; next }
                               { print > "outfile1" }' infile
    

    The first pattern checks if the line matches our split line and increments a flag if so; the second line checks if the flag if set, and if so, prints to the second output file and skips the last pattern/action; the third action is executed if the flag is not set and prints to the first output line.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。