[SYNTAX] sed command

Unix C++ :: UNIX CPP :: UNIX :: SYNTAX

Go down

[SYNTAX] sed command

Post by Christopher on Sun Mar 14, 2010 2:36 pm

sed, a special editor for modifying files automatically. If you want to write a program to make changes in a file, sed is the tool to use.

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

Substitution (S)
The substitute command changes all occurrences of the regular expression into a new value.

Code:
$ cat 1.txt
hi u der
make hi files wonderful
things computer windows hi
hi make ubuntu files
recover delete hi things
computer
computerjee

$ sed 's/hi/HI/g' 1.txt
HI u der
make HI files wonderful
tHIngs computer windows HI
HI make ubuntu files
recover delete HI tHIngs
computer
computerjee

/* it ll replace only lines which contains delete */

$ sed '/delete/s/hi/HI/g' 1.txt
hi u der
make hi files wonderful
things computer windows hi
hi make ubuntu files
recover delete HI tHIngs
computer
computerjee


Transform (y)
If you wanted to change a word from lower case to upper case, you could write 26 character substitutions, converting "a" to "A," etc. Sed has a command that operates like the tr program. It is called the "y" command.

Code:
$ sed 'y/abc/ABC/' 1.txt
hi u der
mAke hi files wonderful
things Computer windows hi
hi mAke uBuntu files
reCover delete hi things
Computer
Computerjee

Multiple Patterns

To check for multiple patterns use -e switch.

Code:
$ sed -e 's/hi/HI/g' -e 's/computer/COMPUTER/g' 1.txt
HI u der
make HI files wonderful
tHIngs COMPUTER windows HI
HI make ubuntu files
recover delete HI tHIngs
COMPUTER
COMPUTERjee

To check for start and end of a line(^ and $)
^ is used to check the start of a line
$ is used to check the end of a line

Code:
$ sed 's/^hi/HI/g' 1.txt
HI u der
make hi files wonderful
things computer windows hi
HI make ubuntu files
recover delete hi things
computer
computerjee

$ sed 's/hi$/HI/g' 1.txt
hi u der
make hi files wonderful
things computer windows HI
hi make ubuntu files
recover delete hi things
computer
computerjee

avatar
Christopher
Admin

Posts : 240
Points : 429
Join date : 2010-02-26
Age : 30

View user profile http://unixcpp.forumotion.com

Back to top Go down

Back to top

- Similar topics

Unix C++ :: UNIX CPP :: UNIX :: SYNTAX

 
Permissions in this forum:
You cannot reply to topics in this forum