• linux 往文件中插入多行


    最近想要实现一个往文件中插入多行的功能,原以为很简单的一件事情,但实际操作中却发现了某些方法中的一些限制,现大略总结如下:

    将一个文件file1 的内容添加到另一文件file2 中

    1)使用cat 加重定向的方式添加到开始处

    cat file1 file2 > temp
    cat temp > file2

    2)使用sed r添加到指定位置,但不能是开始处

    #将文件new2.txt中的数据添加到new.txt的第一行后
    sed '1r new2.txt' new.txt  

    3)使用sed i 添加多行数据到指定位置,但直接添加从文件读取的内容时,则会报错

    ii 添加多行数据

    #在文件开始处添加两行数据
    sed -i '1i a\nb' file2
    
    content='a\nb'
    sed -i '1i '$content'' file2

    ii 读取文件file1的内容到变量,再添加到文件file2 中,会报错

    ubuser@ubuntu:/var/www/qpy_html$ cat file1
    a
    bb
    c
    ubuser@ubuntu:/var/www/qpy_html$ content=`cat file1`
    ubuser@ubuntu:/var/www/qpy_html$ sed -i '1i '$content'' file2
    sed: can't read bb: No such file or directory
    sed: can't read c: No such file or directory
  • 相关阅读:
    七种常见的回归分析—转载
    Python模块之 __future__ 转载
    Java 快速排序
    在给定范围内产生指定个数不重复的随机数
    Java 冒泡排序
    jquery文本框效果
    jquery复选框
    struts2下的Ajax
    java线程系列---Runnable和Thread的区别
    System.getProperty("user.dir")
  • 原文地址:https://www.cnblogs.com/mianbaoshu/p/16223808.html
Copyright © 2020-2023  润新知