190 likes | 347 Views
sed. Dr. Tran, Van Hoai Faculty of Computer Science and Engineering HCMC Uni. of Technology hoai@cse.hcmut.edu.vn. What is " sed "?. sed = stream editor noninteractive , script interpreting input: file, pipe , keyboard output: standard output
E N D
sed Dr. Tran, Van Hoai Faculty of Computer Science and Engineering HCMC Uni. of Technology hoai@cse.hcmut.edu.vn
What is "sed"? • sed = stream editor • noninteractive, script interpreting • input: file, pipe, keyboard • output: standard output • Useful for substitutions on data streams going thru pipelines • "tr" also can be used for substitutions • sed can do more
Typical uses • Edit files automatically • Simplifying repetitive edits to multiple files • Writing conversion programs
Examples (1) 100xyz1000.0xyz50 400xyz1034xyz20445 300xyz304xyz9344 • How to replace "abc" by "\t"? • Can we do by "tr"? • We can do by "sed" in one command sed 's/abc/\t/g' <file> 100 1000.0 50 400 1034 20445 300 304 9344
Components • s substitute command • /../../ delimiter • abc search pattern (regex) • \t replace pattern (regex)
How sed works internally? • Each line copied into a buffer (pattern space) • sedworks on buffer, not the original file • Allsed commands applied to each line • unless line addressing is specified • subsequent commands operate on current line • sed has a hold space for later retrieval
Syntax • Default options sed [-n] [-e] 'command' files -e next argument is an editing command sed [-n] [-f] scriptfile file(s) -f next argument is a script file -n suppress default output • Additional options (man pages)
sed commands • General form [address [,address]][!]command [arguments] • Pattern addressing (0, 1, or more addresses)
Example (3) • Remove "shell comments" • Remove "C/C++ comments" • Remove assign statements 1000 100 100 # This is a comment 60 60 80 // comment in C++ thisVariable = pow( 10, 100 ); 100.0 60 1000 90 /* This is a comment in C */ Well, this is a sentence in natural language
Many commands to a match • Using braces "{ }" • Syntax [/pattern/[,/pattern/]]{ command 1 command 2 }
Global replacement • By default, UNIX works on line-based principle • read a line, perform an operation on the line • By default, sed only work on first occurrence • "s/xx/yy" only replaces the first "xx" to "yy" • "s/xx/yy/g" replaces all "xx"
Reusing matched string • By "&" • Change "abc" to "(abc)" sed –e 's/abc/(abc)/g' c.txt sed –e 's/abc/(&)/g' c.txt
Specifying pattern • By "/1", "/2", etc • Keep the first word, delete the second s/\([a-zA-Z]\{1,\}\)* //2
What is it ? sed 's/[^:]*//2' </etc/passwd >/etc/password.new
awk is NEXT