Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I escape the vertical bar when doing command line with Ruby?

Tags:

windows

ruby

cmd

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.

like image 998
SwiftMango Avatar asked Sep 28 '12 17:09

SwiftMango


People also ask

How do you escape command?

Three Ways to Escape Spaces on WindowsBy enclosing the path (or parts of it) in double quotation marks ( ” ). By adding a caret character ( ^ ) before each space. (This only works in Command Prompt/CMD, and it doesn't seem to work with every command.) By adding a grave accent character ( ` ) before each space.

What is escape in command line?

Escaping is a method of quoting single characters. The escape (\) preceding a character tells the shell to interpret that character literally. With certain commands and utilities, such as echo and sed, escaping a character may have the opposite effect - it can toggle on a special meaning for that character.


1 Answers

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.

like image 134
GorrillaMcD Avatar answered Oct 13 '22 02:10

GorrillaMcD