3

I want to replace the backslash in the string page_path\example_filename.txt with a forward slash. I also want to be able to run this on a large file system and have it recursively search all directories.

I found someone on the web who said to use grep, xargs, and sed but I wasn't able to get it to work. I've been trying different variations on delimiters and escape characters, but didn't get it.

Here is the command I was trying to run:
grep -lr -e 'page_path\\' * | xargs sed -i 's/page_path\/page_path//g'

Thanks in advance.

  • This might interest you – Gowtham Mar 21 '12 at 18:11
3

Also you can use find for that:

find /your/path -type f -exec grep -l 'page_path\\' {} \; -exec sed -i 's#page_path\\#page_path/#g' {} \;

The second exec will be executed only if the first one was succeed, and you won't get problems with unprintable or escape needing characters in file names.

  • Why are you using grep with -l here instead of -q ? – don_crissti Aug 1 '16 at 11:36
  • just to indicate list of files which were changed. but -q is also an option :) – rush Aug 1 '16 at 16:16
5

With grep | xargs, you get problems with whitespaces in filenames. You can avoid this problem by using: grep -lZr ... | xargs -0 sed ... which uses zero bytes as delimiter.

And now regarding the sed command: The trick is that you can use instead of s/a/b/ any other character, e.g. s#a#b#:

 sed -i 's#page_path\\#page_path/#g'
  • 1
    FYI, grep has a -Z option for null-delimited file names, so grep -Z ... | xargs -0 ... is the generally accepted way to do that. – Kevin Mar 21 '12 at 18:26
  • cool, didn't know any character could work as a delimiter in sed – Anthony Elliott Mar 22 '12 at 13:39

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.