Linux sed 命令指南 (sed command cheatsheet)
By Long Luo
Sed Commands Options Description Exit sed without processing any more commands or input. Delete the pattern space; immediately start next cycle. Print out the pattern space (to the standard output). Appending text after a line. insert text before a line. = Print out the current input line number (with a trailing newline). Replaces the line(s) with text. w Write the pattern space to filename. Empty the content of the pattern space. Delete text in the pattern space up to the first newline , restart cycle if pattern space contains newlines. Execute the command that is found in the pattern space. F Print the file name of the current input file. Reads file filename. n N Read/append the next line of input into the pattern space. W Write the first line of the current pattern space to filename Exchange the contents of the hold and pattern spaces. Transliterate any characters in the pattern space.
Command Options Options Description -i[SUFFIX] Edit files in place (make backup if SUFFIX supplied). -n Suppress automatic printing of pattern space. -f add the contents of script-file to the commands to be executed -e Execute multiple sed commands -r or -E Use extended regular expressions (supports ‘+’, ‘(’, ‘)’)■ -s Consider files as separate rather than as a single, continuous stream. -c Copy the input to the standard output. -I pecify the desired line-wrap length for the I command. Command Flags Flags Description g Global substitution - Replace all occurrences in each line. Execute shell command after substitution. w Save only the substituted lines to a specified file. Perform case-insensitive pattern matching. p Print only the substituted lines. 1,2,4,… Substitute the nth occurrence- Replace specific occurrence of a pattern.
BASIC EXAMPLES
$ seq |sed $ seq | sed -n $ sed ‘/warning/i # This is a warning’ logfile $ cod -o ‘<c/corvor/now-corvor/;c/port/8080/;}’ config.-conf
REPLACING TEXT $ sed s/old/new/g file.txt $ sed ‘4 s/old/new/’ file.txt $ sed s/old/new/3 file.txt $ sed ‘s/A//’ file.txt $ sed -n 7important/w important_lines.txt’ logfile $ sed 7hello/s/world/universe/’ file.txt
APPEND AND PREPEND TEXT $ sed -n 7hello/p’ file.txt $ sed -n 7hello/lp’ file.txt $ sed -n 7hellQ/lp’ file,txt $ sed ‘2a Text after line 2’ file.txt $ sed ‘\(a THE END!' file.txt\) sed ’s/old/new/’ config.conf
• • • DELETING LINES $ sed 1,4d’ file.txt $ sed ‘6~4d’ file.txt $ sed ‘\(d' file.txt\) sed 7 AErrors/d’ file.txt $ sed 7 A\(/d' file.txt\) sed 7 A#/d’ file.txt $ sed ’3d’file t¥t
• • • OPTIONS EXAMPLES $ sed -n 7error/p’ syslog.log $ sed -e ‘s/server-01/server-02/’ -e ‘s/port=8080/port=9090/’ app.conf $ sed -i.bak ‘s/v3.3.2/3.4.1/’ app.conf $ sed .r ‘s/(error|warning)/info/’ syslog Ing $ bed -b ‘b/liubuidiiie/bei vei/1 /eiu/Luunf $ sed -n -e ’1,5C' -e’ I his is a new line.’ source.txt destination.txt $ seo -T repiace_pauerns.sea conng.ixi sysxplore.com $ sed -I long_text.txt