02.linux命令之批量替换文件内容sed

 1.sed详解

用来自动编辑一个或多个文件;简化对文件的反复操作;编写转换程序等这里主要是批量的替换文件内容

1)命令格式:

sed [可选参数] {script-only-if-no-other-script} [文件]

 2).主要的参数有一下内容:

Usage: sed [OPTION]... {script-only-if-no-other-script} [input-file]...

  -n, --quiet, --silent
                 suppress automatic printing of pattern space
  -e script, --expression=script
                 add the script to the commands to be executed
  -f script-file, --file=script-file
                 add the contents of script-file to the commands to be executed
  --follow-symlinks
                 follow symlinks when processing in place
  -i[SUFFIX], --in-place[=SUFFIX]
                 edit files in place (makes backup if SUFFIX supplied)
  -c, --copy
                 use copy instead of rename when shuffling files in -i mode
  -b, --binary
                 does nothing; for compatibility with WIN32/CYGWIN/MSDOS/EMX (
                 open files in binary mode (CR+LFs are not treated specially))
  -l N, --line-length=N
                 specify the desired line-wrap length for the `l' command
  --posix
                 disable all GNU extensions.
  -r, --regexp-extended
                 use extended regular expressions in the script.
  -s, --separate
                 consider files as separate rather than as a single continuous
                 long stream.
  -u, --unbuffered
                 load minimal amounts of data from the input files and flush
                 the output buffers more often
  -z, --null-data
                 separate lines by NUL characters
  --help
                 display this help and exit
  --version
                 output version information and exit

  参数解析:

  • -e<script>或--expression=<script> 以选项中指定的script来处理输入的文本文件。
  • -f<script文件>或--file=<script文件> 以选项中指定的script文件来处理输入的文本文件。
  • -h或--help 显示帮助。
  • -n或--quiet或--silent 仅显示script处理后的结果。
  • -V或--version 显示版本信息。
  • a :新增, a 的后面可以接字串,而这些字串会在新的一行出现(目前的下一行)~
  • c :取代, c 的后面可以接字串,这些字串可以取代 n1,n2 之间的行!
  • d :删除,因为是删除啊,所以 d 后面通常不接任何咚咚;
  • i :插入, i 的后面可以接字串,而这些字串会在新的一行出现(目前的上一行);
  • p :打印,亦即将某个选择的数据印出。通常 p 会与参数 sed -n 一起运行~
  • s :取代,可以直接进行取代的工作哩!通常这个 s 的动作可以搭配正规表示法!例如 1,20s/old/new/g 就是啦!

3)栗子 

替换文件内容

sed 's/要被取代的字串/新的字串/g'
如:sed 's/a/b/g' xx.txt

添加内容

sed '1i 添加的内容' file  #在第一行前添加字符串  
sed '$i 添加的内容' file  #在最后一行行前添加字符串  
sed '$a添加的内容' file  #在最后一行行后添加字符串 
sed -e 10a\添加内容 file #在第10行后添加字符串 

栗子
sed '1i 哈哈哈' a-111.txt   #在a-111.txt第一行添加 内容 哈哈哈

sed '$i 哈哈哈' a-111.txt   #在a-111.txt最后一行前添加 内容 哈哈哈

sed '$a 哈哈哈' a-111.txt   #在a-111.txt最后一行后添加 内容 哈哈哈

sed -e 10a\哈哈哈 a-111.txt   #在a-111.txt最后一行后添加 内容 哈哈哈

  

 

未完待续。。。

猜你喜欢

转载自www.cnblogs.com/code111/p/9156928.html
今日推荐