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 ?
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.
str.chompwll remove the newline character from strings.
str.chop only removes the last character.
Why are you calling out to the shell for something so simple:
h, p1, p2, u = l.split /:/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With