Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get rid of newline from shell commands in Ruby

I am trying to run simple shell commands in my script, but am unable to get rid of new lines even using chomp or chop.

Is there something I am missing ?

      u=`echo  '#{l}' | cut -d: -f4`.chop()
      p2=`echo '#{l}' | cut -d: -f3`.chop()
      p1=`echo '#{l}' | cut -d: -f2`.chop()
      h=`echo  '#{l}' | cut -d: -f1`.chop()


#     **Cant get newlines to go after p1 and p2 !! ??**
      path="#{p1}/server/#{p2}abc"
      puts path


 Output:
 /usr (p1)
 /server
 /bin (p2) abc 
 Expected Output:
 /usr/server/binabc

Any suggestions ?

As per some suggestions, changed my code to :

h, p1, p2, u = l.split /:/
u.strip 
u.chomp

puts u.inspect

Output: "string\n"

Basically I had tried using chomp before and was hitting the same problem. Do I need to call chomp in a different way or add any gem ?

like image 213
codeObserver Avatar asked Sep 23 '11 18:09

codeObserver


3 Answers

Use either String#strip to remove all wrapping whitespace, or String#chomp (note the 'm') to remove a single trailing newline only.

String#chop removes the last character (or \r\n pair) which could be dangerous if the command does not always end with a newline.

I assume that your code did not work because the results had multiple newlines\whitespace at the end of the output. (And if so, strip will work for you.) You can verify this, however, by removing the call to chop, and then using p u or puts u.inspect to see what characters are actually in the output.

And for your information, it's idiomatic in Ruby to omit parentheses when calling methods that take no arguments, e.g. u = foo.chop.

like image 82
Phrogz Avatar answered Oct 28 '22 08:10

Phrogz


str.chompwll remove the newline character from strings. str.chop only removes the last character.

like image 41
lukad Avatar answered Oct 28 '22 08:10

lukad


Why are you calling out to the shell for something so simple:

h, p1, p2, u = l.split /:/
like image 21
glenn jackman Avatar answered Oct 28 '22 08:10

glenn jackman