How can I escape the vertical bar when doing comma

2020-04-03 02:37发布

问题:

I have this command line input in Windows:

dir /b | ruby -ne 'f=$_.chomp;File.read(f).each_line{|line| print f if line =~ /helloworld/};'

This line is to find all files under current directory with helloworld in it. (I understand there are many other ways to do this but the post is not focusing on that)

My question is:

This line gives error saying line is not a valid command. Then I realized | in Ruby as a brace for block variable is a pipe sign in cmd. I tried to change the whole line into double quoted and escape the | sign but no success. How can I escape the vertical bar |?

Please don't answer other ways to do the task such as using other tools like grep, find, sed or awk, or change the block into for loop.

回答1:

I found this microsoft.com page that says the following about pipes and special characters:

The ampersand (&), pipe (|), and parentheses ( ) are special characters that must be preceded by the escape character (^) or quotation marks when you pass them as arguments.



回答2:

Single quotes seem to be your problem. Use double quotes instead, because they're required for Windows (though Unix can understand either).

This works for me in Windows:

C:\tmp\ruby>echo helloworld > foo.txt

C:\tmp\ruby>dir /b | ruby -ne "f=$_.chomp;File.read(f).each_line{|line| print f if line =~ /helloworld/};"
foo.txt

I know you mentioned that you tried double quotes, but if you paste what you actually tried, I can see if something else was wrong.



标签: ruby windows cmd