I use Visual Studio for my C# development while using Cygwin for some of the tasks that require scripting. Recently I wanted to change all occurrences of string AAA to BBB in my project's files. I started with old trusty sed but, to my dismay, it changed DOS new line sequences to Unix ones.

Here's what I used:

sed -i 's/AAA/BBB/g' $(grep -rl AAA /cygdrive/c/project_path)

It seems there is no sed switch that would do what I want. Is there some other Unix tool that could help me?

EDIT: In between C# files there are some other scripts that have Unix new line characters. It would be best if this tool didn't change them to DOS ones. :)

  • If you use Visual Studio for development, Cygwin for scripting and you don't want 'other scripts' to be affected by the change, why can't you simply use the Replace embedded into VS? – matcheek Jun 20 '12 at 11:54
  • I can. But since I like Linux a lot and I do a lot of programming under Linux for my studies and personal projects, I always try to find a FOSS solution to my problems. – mczers Jun 20 '12 at 13:44

There gotta be a built-in function for this in VS.

If not, you can use good old vi:

vi +'bufdo %s/AAA/BBB/g | update' +q $(grep -rl AAA /cygdrive/c/project_path)
  • This worked perfect. See my reply to @matcheek comment for why I didn't want to use VS function. – mczers Jun 20 '12 at 13:55

You can use Cygwin's perl instead. Typical sed commands map easily to Perl. Note that the regex syntax is different (extended regular expressions in Perl, basic regular expressions in sed).

perl -i -pe 's/AAA/BBB/g' $(grep -rl AAA /cygdrive/c/project_path)

Note that parsing the result of a command substitution as a list of files is brittle. It'll break if there are spaces or backslashes in the file names; both are fairly common under Windows (you get backslashes when a path hasn't been translated from native to cygwin, for example when it comes from an environment variable). Use xargs -d '\n' instead (there are no newlines in Windows file names).

grep -rl AAA /cygdrive/c/project_path | xargs -d '\n' perl -i -pe 's/AAA/BBB/g'

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.