1

I am maintaing a linux driver and I want to replace all %p in driver with %pK. For doing this i used following command.

grep "%p[^K]" -Rl . | xargs sed -i 's/%p[^K]/%pK/g'

It fails in below case.

%p-%p --> %pK%pK (hyphen is removed)

Please suggest proper regular expressionfor sed command to work.

4
  • I think you are looking for a way to assert that %p is not followed by K and then replace... one way is to use perl with lookarounds... ex: echo '%p-%p' | perl -pe 's/%p(?!K)/%pK/g' – Sundeep Oct 28 '16 at 7:07
  • @Sundeep I am trying to do same, but I want to make changes in all files in all position where %p is present ( not %pK). So is there any way to do same with sed. I tried following but did not work. grep "%p[^K]" -Rl . | xargs sed -i 's/%p(?!K)/%pK/g' – Trishansh Bhardwaj Oct 28 '16 at 8:28
  • try echo '%p-%p' | sed -E 's/%p([^K]|$)/%pK\1/g'... and I would suggest grep -RlZ '%p[^K]' | xargs -0 sed -i -E 's/%p([^K]|$)/%pK\1/g' to prevent issues with filenames containing special characters... also I hope you are trying this out on test folders instead of directly applying changes on actual files.. you can do that once you have a working solution – Sundeep Oct 28 '16 at 8:33
  • sed doesn't have lookaround regex, that is why I suggested perl.. – Sundeep Oct 28 '16 at 8:40
2

The sed replacement in the question would remove any characters after a %p, not just dashes, since the [^K] is part of the matched string. You can work around that by capturing the character after %p with (escaped) parenthesis, and putting it back with \1. In sed:

$ echo '%p %p %pK' | sed 's/%p\([^K]\)/%pK\1/g'
%pK %pK %pK

Though you might want to use [^a-zA-Z] or similar just in case you were to use other modifiers for %p.

0

Following command did magic for me

for fname in $(grep "%p[^K]" -Rl .); do perl -pi -e 's/%p(?!K)/%pK/g' $fname; done

Thanks Sundeep, Your comment helped a lot. :)

1
  • That is an answer, though it would be much better with an explanation, so it would be independent of the comments. – ilkkachu Oct 28 '16 at 9:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.