【三剑客】之sed使用总结

系统+安全 Liemer_Lius 21℃

sed作为Linux三剑客命令之一,使用场景极多,总结常用和比较高级的用法,供后续参考。

sed的选项

> sed --help
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

示例:sed -i 实现文件字符串替换

> sed -i.bak 's/j/a/g' a.txt   # -i可以用替换字符串的形式编辑文件,-i后面紧跟一个字符串(不能加空格),可以在替换前将文件做一个备份,比如位置是.bak,备份文件就是file.bak
> ls -lhrt
total 12K
-rw-------. 1 root root 1.3K Apr 29 07:37 anaconda-ks.cfg
-rw-r--r--  1 root root   25 Apr 30 03:51 a.txt.bak
-rw-r--r--  1 root root   25 Apr 30 03:53 a.txt
> diff a.txt a.txt.bak 
1c1
< dlkdakakadfaadkfaakdafka
---
> dlkdjkjkjdfjadkfjakdjfkj

 

转载请注明:skelchina.com » 【三剑客】之sed使用总结

喜欢 (1)