Hans Deragon Hans Deragon - 13 days ago 7
Ruby Question

Ruby one liner to replace only lines that match, discard others

Looking for the ruby one liner substitute to print out a substitution only if the line matches the regular expression:

echo -e "Line 1\nLine 2\nLine 3" | perl -ne "print if s/Line 2/Line 2 replaced, others discarded/g"


Input:

Line 1
Line 2
Line 3


Output:

Line 2 replaced, others discarded

Answer

As I know, there is no equivalent to -ne shorthand in ruby. So it will be little longer:

echo -e "Line 1\nLine 2\nLine 3" | ruby -e 'puts $<.read.lines.map {|l| l =~ /Line 2/ ? l.gsub(/Line 2/, "Line 2 replaced, others discarded") : nil }.compact'

Where:

  • $< also ARGF (docs) is Stream for file argument or STDIO
  • $<.read will read it all to string
  • $<.read.lines split by new line character, returns array
  • map {|l| ... } will collect result of expression in a block to new array
  • l =~ /Line 2/ check if string match Regex
  • l.gsub(/Line 2/, "Line 2 replaced") will replace all "Line 2" to "Line 2 replaced"
  • .compact will remove nil values from array (return new array without nil's)
  • puts [] will print each element of array on new line

Probably ruby is not a best chose for this task, I would choose sed or do it in text editor. Most of text editors can find and replace by regex nowdays