I am searching for a specific pattern and replacing with ( ) for matched pattern .I am not getting the expected result .....
Here is the file
cat test
cool
change
Frinto Francis
Frinto cool
change Attitude
/usr/bin
sed 's/[a-z,/]*/( & )/' test
( cool )
( change )
( )Frinto Francis
( )Frinto cool
( change ) Attitude
( /usr/bin )
whereas the expected result should be
( cool )
( change )
Frinto Francis
Frinto cool
( change ) Attitude
( /usr/bin )
what is wrong in the command ...why is open and closed bracket shows at beginning of unmatched pattern .
Because [a-z,/]*
matches 0 or more occurrences of [a-z,/]
(i.e. it matches a null string too).
Depending on your sed version, you could try the following ones:
% sed 's/^[a-z,/][a-z,/]*/( & )/' infile
( cool )
( change )
Frinto Francis
Frinto cool
( change ) Attitude
( /usr/bin )
% sed 's/^[a-z,/]\+/( & )/' infile
( cool )
( change )
Frinto Francis
Frinto cool
( change ) Attitude
( /usr/bin )
As you see, you need to anchor (^) the pattern too, otherwise you'll get a different result:
% sed 's/[a-z,/][a-z,/]*/( & )/' infile
( cool )
( change )
F( rinto ) Francis
F( rinto ) cool
( change ) Attitude
( /usr/bin )
The following variation of radoulov's suggestion should also be portable:
sed 's/^[a-z,/]\{1,\}/( & )/' infile
And remember, the a-z range expression is only defined in the POSIX/C locale.
Regards,
Alister