Sed - An Introduction and Tutorial by Bruce Barnett
With no flags,the first matched substitution is changed. With the "g" option,all matches are changed. If you want to modify a particular pattern that is not the first one on the line,you could use "(" and ")" to mark each pattern,and use "1" to put the first pattern back unchanged. This next example keeps the first word on the line but deletes the second: sed 's/([a-zA-Z]*) ([a-zA-Z]*) /1 /' Yuck. There is an easier way to do this. You can add a number after the substitution command to indicate you only want to match that particular pattern. Example: sed 's/[a-zA-Z]* //2' You can combine a number with the g (global) flag. For instance,if you want to leave the first word alone,but change the second,third,etc. to be DELETED instead,use /2g: sed 's/[a-zA-Z]* /DELETED /2g' Don't get /2 and 2 confused. The /2 is used at the end. 2 is used in inside the replacement field. Note the space after the "*" character. Without the space,?sed?will run a long,long time. (Note: this bug is probably fixed by now.) This is because the number flag and the "g" flag have the same bug. You should also be able to use the pattern sed 's/[^ ]*//2' but this also eats CPU. If this works on your computer,and it does on some UNIX systems,you could remove the encrypted password from the password file: sed 's/[^:]*//2' /etc/password.new But this didn't work for me the time I wrote this. Using "[^:][^:]*" as a work-around doesn't help because it won't match an non-existent password,and instead delete the third field,which is the user ID! Instead you have to use the ugly parenthesis: sed 's/^([^:]*):[^:]:/1::/' /etc/password.new You could also add a character to the first pattern so that it no longer matches the null pattern: sed 's/[^:]*:/:/2' /etc/password.new The number flag is not restricted to a single digit. It can be any number from 1 to 512. If you wanted to add a colon after the 80th character in each line,you could type: sed 's/./&:/80' You can also do it the hard way by using 80 dots: sed 's/^................................................................................/&:/' By default,?sed?prints every line. If it makes a substitution,the new text is printed instead of the old one. If you use an optional argument to sed,"sed -n," it will not,print any new lines. I'll cover this and other options later. When the "-n" option is used,the "p" flag will cause the modified line to be printed. Here is one way to duplicate the function of?grep?with?sed: sed -n 's/pattern/&/p' |