概念

文本处理工具,可以看成一种特殊的程序设计语言,用来高效地批量处理文本数据。

特点

1. 非交互式编辑(与vi 编辑器相比)
2. 面向数据流
3. 可以使用正则表达式
4. 有一个缓冲区(模式空间)的概念,是理解 sed 的关键

sed的两种语法格式

sed [OPTIONS]... 'COMMAND' [FILE]...
sed [OPTIONS] -f SCRIPTFILE [FILE]...

sed指令的语法形式 (指令的地址和模式空间的行匹配)

[address[, address]][!]command

[address1, address2]command

[line-address]command

address {
command1
command2
command3
}

sed常用选项(OPTIONS)

-e    --expression

-f    --file

-i    --in-place

-n

sed常用命令(COMMAND)

sed的编辑命令有24个,关于每个编辑命令的用途的详细信息,参考sed的man参考手册。

常用的有下面几个,

追加(a)
更改(c)
删除(d)
插入(i)
替换(s)
打印(l)
打印行号(=)
转换(y)

sed替换标记

对于替换命令s,有以下的常用的替换标记,

 g 表示行内全面替换;p 表示打印行;w 表示把行写入一个文件;x 表示互换模板块中的文本和缓冲区中的文本;y 表示把一个字符翻译为另外的字符(但是不用于正则表达式);\1 子串匹配标记;& 已匹配字符串标记;

sed_help文档(help)

$ sed --help
Usage: sed [OPTION]... {script-only-if-no-other-script} [input-file]...-n, --quiet, --silentsuppress automatic printing of pattern space-e script, --expression=scriptadd the script to the commands to be executed-f script-file, --file=script-fileadd the contents of script-file to the commands to be executed--follow-symlinksfollow symlinks when processing in place-i[SUFFIX], --in-place[=SUFFIX]edit files in place (makes backup if SUFFIX supplied)-c, --copyuse copy instead of rename when shuffling files in -i mode-b, --binarydoes nothing; for compatibility with WIN32/CYGWIN/MSDOS/EMX (open files in binary mode (CR+LFs are not treated specially))-l N, --line-length=Nspecify the desired line-wrap length for the `l' command--posixdisable all GNU extensions.-r, --regexp-extendeduse extended regular expressions in the script.-s, --separateconsider files as separate rather than as a single continuouslong stream.-u, --unbufferedload minimal amounts of data from the input files and flushthe output buffers more often-z, --null-dataseparate lines by NUL characters--helpdisplay this help and exit--versionoutput version information and exitIf no -e, --expression, -f, or --file option is given, then the first
non-option argument is taken as the sed script to interpret.  All
remaining arguments are names of input files; if no input files are
specified, then the standard input is read.GNU sed home page: <http://www.gnu.org/software/sed/>.
General help using GNU software: <http://www.gnu.org/gethelp/>.
E-mail bug reports to: <bug-sed@gnu.org>.
Be sure to include the word ``sed'' somewhere in the ``Subject:'' field.

sed_man手册(man)

$ man sedSED(1)                    BSD General Commands Manual                   SED(1)NAMEsed -- stream editorSYNOPSISsed [-Ealn] command [file ...]sed [-Ealn] [-e command] [-f command_file] [-i extension] [file ...]DESCRIPTIONThe sed utility reads the specified files, or the standard input if no files are specified, modifying the input as speci-fied by a list of commands.  The input is then written to the standard output.A single command may be specified as the first argument to sed.  Multiple commands may be specified by using the -e or -foptions.  All commands are applied to the input in the order they are specified regardless of their origin.The following options are available:-E      Interpret regular expressions as extended (modern) regular expressions rather than basic regular expressions(BRE's).  The re_format(7) manual page fully describes both formats.-a      The files listed as parameters for the ``w'' functions are created (or truncated) before any processing begins, bydefault.  The -a option causes sed to delay opening each file until a command containing the related ``w'' functionis applied to a line of input.-e commandAppend the editing commands specified by the command argument to the list of commands.-f command_fileAppend the editing commands found in the file command_file to the list of commands.  The editing commands shouldeach be listed on a separate line.-i extensionEdit files in-place, saving backups with the specified extension.  If a zero-length extension is given, no backupwill be saved.  It is not recommended to give a zero-length extension when in-place editing files, as you risk cor-ruption or partial content in situations where disk space is exhausted, etc.-l      Make output line buffered.-n      By default, each line of input is echoed to the standard output after all of the commands have been applied to it.The -n option suppresses this behavior.The form of a sed command is as follows:[address[,address]]function[arguments]Whitespace may be inserted before the first address and the function portions of the command.Normally, sed cyclically copies a line of input, not including its terminating newline character, into a pattern space,(unless there is something left after a ``D'' function), applies all of the commands with addresses that select that pat-tern space, copies the pattern space to the standard output, appending a newline, and deletes the pattern space.Some of the functions use a hold space to save all or part of the pattern space for subsequent retrieval.Sed AddressesAn address is not required, but if specified must be a number (that counts input lines cumulatively across input files), adollar (``$'') character that addresses the last line of input, or a context address (which consists of a regular expres-sion preceded and followed by a delimiter).A command line with no addresses selects every pattern space.A command line with one address selects all of the pattern spaces that match the address.A command line with two addresses selects an inclusive range.  This range starts with the first pattern space that matchesthe first address.  The end of the range is the next following pattern space that matches the second address.  If the sec-ond address is a number less than or equal to the line number first selected, only that line is selected.  In the case whenthe second address is a context address, sed does not re-match the second address against the pattern space that matchedthe first address.  Starting at the first line following the selected range, sed starts looking again for the firstaddress.Editing commands can be applied to non-selected pattern spaces by use of the exclamation character (``!'') function.Sed Regular ExpressionsThe regular expressions used in sed, by default, are basic regular expressions (BREs, see re_format(7) for more informa-tion), but extended (modern) regular expressions can be used instead if the -E flag is given.  In addition, sed has thefollowing two additions to regular expressions:1.   In a context address, any character other than a backslash (``\'') or newline character may be used to delimit theregular expression.  Also, putting a backslash character before the delimiting character causes the character to betreated literally.  For example, in the context address \xabc\xdefx, the RE delimiter is an ``x'' and the second ``x''stands for itself, so that the regular expression is ``abcxdef''.2.   The escape sequence \n matches a newline character embedded in the pattern space.  You cannot, however, use a literalnewline character in an address or in the substitute command.One special feature of sed regular expressions is that they can default to the last regular expression used.  If a regularexpression is empty, i.e., just the delimiter characters are specified, the last regular expression encountered is usedinstead.  The last regular expression is defined as the last regular expression used as part of an address or substitutecommand, and at run-time, not compile-time.  For example, the command ``/abc/s//XXX/'' will substitute ``XXX'' for the pat-tern ``abc''.Sed FunctionsIn the following list of commands, the maximum number of permissible addresses for each command is indicated by [0addr],[1addr], or [2addr], representing zero, one, or two addresses.The argument text consists of one or more lines.  To embed a newline in the text, precede it with a backslash.  Other back-slashes in text are deleted and the following character taken literally.The ``r'' and ``w'' functions take an optional file parameter, which should be separated from the function letter by whitespace.  Each file given as an argument to sed is created (or its contents truncated) before any input processing begins.The ``b'', ``r'', ``s'', ``t'', ``w'', ``y'', ``!'', and ``:'' functions all accept additional arguments.  The followingsynopses indicate which arguments have to be separated from the function letters by white space characters.Two of the functions take a function-list.  This is a list of sed functions separated by newlines, as follows:{ functionfunction...function}The ``{'' can be preceded by white space and can be followed by white space.  The function can be preceded by white space.The terminating ``}'' must be preceded by a newline or optional white space.[2addr] function-listExecute function-list only when the pattern space is selected.[1addr]a\text    Write text to standard output immediately before each attempt to read a line of input, whether by executing the``N'' function or by beginning a new cycle.[2addr]b[label]Branch to the ``:'' function with the specified label.  If the label is not specified, branch to the end of thescript.[2addr]c\text    Delete the pattern space.  With 0 or 1 address or at the end of a 2-address range, text is written to the standardoutput.[2addr]dDelete the pattern space and start the next cycle.[2addr]DDelete the initial segment of the pattern space through the first newline character and start the next cycle.[2addr]gReplace the contents of the pattern space with the contents of the hold space.[2addr]GAppend a newline character followed by the contents of the hold space to the pattern space.[2addr]hReplace the contents of the hold space with the contents of the pattern space.[2addr]HAppend a newline character followed by the contents of the pattern space to the hold space.[1addr]i\text    Write text to the standard output.[2addr]l(The letter ell.)  Write the pattern space to the standard output in a visually unambiguous form.  This form is asfollows:backslash          \\alert              \aform-feed          \fcarriage-return    \rtab                \tvertical tab       \vNonprintable characters are written as three-digit octal numbers (with a preceding backslash) for each byte in thecharacter (most significant byte first).  Long lines are folded, with the point of folding indicated by displayinga backslash followed by a newline.  The end of each line is marked with a ``$''.[2addr]nWrite the pattern space to the standard output if the default output has not been suppressed, and replace the pat-tern space with the next line of input.[2addr]NAppend the next line of input to the pattern space, using an embedded newline character to separate the appendedmaterial from the original contents.  Note that the current line number changes.[2addr]pWrite the pattern space to standard output.[2addr]PWrite the pattern space, up to the first newline character to the standard output.[1addr]qBranch to the end of the script and quit without starting a new cycle.[1addr]r fileCopy the contents of file to the standard output immediately before the next attempt to read a line of input.  Iffile cannot be read for any reason, it is silently ignored and no error condition is set.[2addr]s/regular expression/replacement/flagsSubstitute the replacement string for the first instance of the regular expression in the pattern space.  Any char-acter other than backslash or newline can be used instead of a slash to delimit the RE and the replacement.  Withinthe RE and the replacement, the RE delimiter itself can be used as a literal character if it is preceded by a back-slash.An ampersand (``&'') appearing in the replacement is replaced by the string matching the RE.  The special meaningof ``&'' in this context can be suppressed by preceding it by a backslash.  The string ``\#'', where ``#'' is adigit, is replaced by the text matched by the corresponding backreference expression (see re_format(7)).A line can be split by substituting a newline character into it.  To specify a newline character in the replacementstring, precede it with a backslash.The value of flags in the substitute function is zero or more of the following:N       Make the substitution only for the N'th occurrence of the regular expression in the pattern space.g       Make the substitution for all non-overlapping matches of the regular expression, not just the firstone.p       Write the pattern space to standard output if a replacement was made.  If the replacement string isidentical to that which it replaces, it is still considered to have been a replacement.w file  Append the pattern space to file if a replacement was made.  If the replacement string is identicalto that which it replaces, it is still considered to have been a replacement.[2addr]t [label]Branch to the ``:'' function bearing the label if any substitutions have been made since the most recent reading ofan input line or execution of a ``t'' function.  If no label is specified, branch to the end of the script.[2addr]w fileAppend the pattern space to the file.[2addr]xSwap the contents of the pattern and hold spaces.[2addr]y/string1/string2/Replace all occurrences of characters in string1 in the pattern space with the corresponding characters fromstring2.  Any character other than a backslash or newline can be used instead of a slash to delimit the strings.Within string1 and string2, a backslash followed by an ``n'' is replaced by a newline character.  A pair of back-slashes is replaced by a literal backslash.  Finally, a backslash followed by any other character (except a new-line) is that literal character.[2addr]!function[2addr]!function-listApply the function or function-list only to the lines that are not selected by the address(es).[0addr]:labelThis function does nothing; it bears a label to which the ``b'' and ``t'' commands may branch.[1addr]=Write the line number to the standard output followed by a newline character.[0addr]Empty lines are ignored.[0addr]#The ``#'' and the remainder of the line are ignored (treated as a comment), with the single exception that if thefirst two characters in the file are ``#n'', the default output is suppressed.  This is the same as specifying the-n option on the command line.ENVIRONMENTThe COLUMNS, LANG, LC_ALL, LC_CTYPE and LC_COLLATE environment variables affect the execution of sed as described inenviron(7).EXIT STATUSThe sed utility exits 0 on success, and >0 if an error occurs.LEGACY DESCRIPTIONWarnings are not generated for unused labels.  In legacy mode, they are.In the -y function, doubled backslashes are not converted to single ones.  In legacy mode, they are.For more information about legacy mode, see compat(5).SEE ALSOawk(1), ed(1), grep(1), regex(3), compat(5), re_format(7)STANDARDSThe sed utility is expected to be a superset of the IEEE Std 1003.2 (``POSIX.2'') specification.The -E, -a and -i options are non-standard FreeBSD extensions and may not be available on other operating systems.HISTORYA sed command, written by L. E. McMahon, appeared in Version 7 AT&T UNIX.AUTHORSDiomidis D. Spinellis <dds@FreeBSD.org>BUGSMultibyte characters containing a byte with value 0x5C (ASCII `\') may be incorrectly treated as line continuation charac-ters in arguments to the ``a'', ``c'' and ``i'' commands.  Multibyte characters cannot be used as delimiters with the ``s''and ``y'' commands.BSD                              May 10, 2005                              BSD

参考:

Linux之sed命令详解 | 《Linux就该这么学》

Linux sed命令完全攻略(超级详细)

https://man.linuxde.net/sed

Linux sed命令 | 浩瀚宇宙 灿烂星空

linux下批量文件处理-字符串替换 | Winddoing's Notes

Linux 文本处理工具——sed相关推荐

  1. linux文本处理脚本题,Linux文本处理工具sed练习题

    1.使用sed命令打印出ifconfig ens33的ip地址 解:(1)ifconfig ens33 | sed -n '2p' | sed 's/.*inet //' | sed 's/netma ...

  2. shell编程之文本处理工具sed

    shell编程之文本处理工具sed 文章目录 shell编程之文本处理工具sed 一.文件编辑器知多少 二.强悍的sed介绍 1. sed用来做啥? 2. sed如何处理文件? 三.sed使用方法介绍 ...

  3. Linux文本编译工具VIM详解

    Linux文本编译工具VIM详解 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.VIM概述 1>.vim简介 1>.vi: 全称Visual editor,即文本编 ...

  4. linux的locate工具,linux文本查找工具之locate、find

    linux文本查找工具之locate.find 一.文件查找分为两类: 1.非实时查找:locate 2.实时查找:find 二.非实时查找:locate 非实时查找:查找速度快.非精准查找.模糊查找 ...

  5. redhat linux 文本处理工具笔记

    Linux文本处理工具:     文本搜索 globbing:             *:p*d /etc/passwd: root grep, egrep, fgrep Global search ...

  6. linux文本处理工具之grep与正则表达式语法

    Grep 介绍 Linux 文本处理三剑客之一,文件过滤工具(另外两剑客为sed:文本编辑工具,awk:文本报告生成器) 拥有着,根据用户指定的"模式"对目标文本逐行进行匹配检查: ...

  7. linux文本分析工具awk解读

    awk是一个强大的文本分析工具,相对于grep的查找.sed的编辑,awk在其对数据分析并生成报告时,显得尤为强大.awk把文件逐行的读入,以空格为默认分隔符将每行切片,切开的部分再进行各种分析处理. ...

  8. Linux文本处理工具和正则表达式

    成功不易,加倍努力! 1 文本编辑工具之神VIM 1.1命令或普通(Normal)模式的基本命令 1.2 插入(Insert)或编辑模式的基本命令 1.3 扩展命令模式基本命令 1.4 vim的寄存器 ...

  9. Linux文本三剑客之sed仗剑走天涯

    一,sed是什么? sed是Strem Editor(流编辑器)缩写,是操作.过滤和转换文本内容的强大工具.对文件内容逐行(行编辑器,一行读取一次,对行编辑)进行处理调用操作并显示到STDOUT,常用 ...

  10. Linux文本处理(grep,sed)

    正则表达式    grep   全面搜索正则表达式并把行打印出来是一种强大的文本搜索工具   能使用正则表达式搜索文本,并把匹配的行打印出来   grep命令常见用法 (1)在文件中搜索一个单词,命令 ...

最新文章

  1. GPU上的基本线性代数
  2. 你的应用是如何被替换的,App劫持病毒剖析
  3. cruzer php sandisk 闪迪u盘量产工具_SanDisk Cruzer Micro下载
  4. Git同步本地项目文件到github
  5. 记录Pandas处理数据的两个小技巧
  6. 使用logrotate分割tomcat日志
  7. 2018:WebRTC开发五大趋势
  8. 纪录片.BBC.数据之趣.The.Joy.of.Data.2016
  9. 微软 2006年7月已试发布 ERP Dynamics AX 简体中文版 4.0 (第一个简体中文版),请下吧 !...
  10. 实验管理员掌握的计算机知识,计算机应用基础知识概述试验.DOC
  11. 微服务集成cas_Spring Cloud(四) Spring Cloud Security集成CAS (单点登录)对微服务认证...
  12. java中int和Integer对比的一些坑
  13. 关于DSP2812的Timer0定时器配置程序的质疑
  14. PHP——AES加解密 +SIGN校验唯一性安全性(Api)
  15. Java 基础 - List 遍历时为什么不能通过 for 循环进行删除,而使用 Iterator 可以 ?
  16. ZJU PTA ds 6-1 Percolate Up and Down
  17. 武汉坚守第六十三天——七九已满疫未退,印度大法上棍棒
  18. 抚躬自问,我该怎样总结我的Q3?
  19. 全球及中国集成电路产业战略规划与运营前景调研报告2022版
  20. 十大SEO排名因素:如何提高百度排名?干货

热门文章

  1. html文字段落i排版,i排版基础操作GIF版
  2. Qt之获取屏幕分辨率
  3. POJ 4001 xiangqi(模拟)
  4. STL之vector的push_back过程详解
  5. java java -cp_java -cp用法
  6. LATEX插入参考文献(两种方法)
  7. keras实现交叉验证以及K折交叉验证
  8. java如何导出excel_JAVA如何导出EXCEL表格
  9. Mapped Statements collection does not contain value for错误可能
  10. 常见的系统漏洞安全扫描修复总结归纳