Quantcast
Channel: sed replacing character in a file - Ask Ubuntu
Viewing all articles
Browse latest Browse all 2

Answer by terdon for sed replacing character in a file

$
0
0

The golden rule in regular expressions is: less is more. Always try and find the simplest expression that is sufficient to target your search string. So instead of trying to match the entire line, look for a small, but unique, string:

$ grep -- -c file
create  cifs.spnego *   *       /usr/sbin/cifs.upcall -c %k

I saved your file as file and, as you can see, there is only one case of -c in the file. So all you need is (note the -i.bak, that will create a backup file):

sed -i.bak 's/-c/-t/' /etc/request-key.conf

If you want to be more prudent and make sure you match only your target line without searching first, just change the -c on any lines starting with create cifs.spnego. Note the use of -E for extended regular expressions and using \s+ (1 or more whitespace) instead of trying to write multiple spaces:

sed -Ei.bak 's/^(create\s+cifs\.spnego.*cifs.upcall\s+)-c/\1 -t/' /etc/request-key.conf

Since you don't need to make any changes after the -c, there is no reason to try and match it: less is more.


The reason your attempt failed is because * is a multiplier in regular expressions, it means "0 or more". So when you have cifs.spnego *cifs.upcall, that looks for cifs.spnego, then 0 or more spaces, followed by cifs.upcall. Your line, however, was:

create  cifs.spnego *   *       /usr/sbin/cifs.upcall  -t %k

To match that, you need to match cifs.spnego, then a space, then a *, then more spaces, and another *, then /usr/sbin/ and only then do you have cifs.upcall. To match all of those, you would need (you need \* to match the character *):

/^create  cifs.spnego \*   \*       cifs.upcall/

Or, since less is more, simply:

/^create  cifs.spnego .*cifs.upcall/

The .* means "anything".


Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images