Get Rid of Newlines from Shell Commands in Ruby

I am trying to run simple shell commands in my script, but I can not 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?

According to some suggestions, changed my code to:

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

Output: "string\n"

I basically tried to use chomp before and ran into the same problem. Do I need to call chomp differently or add some kind of stone?

+6
source share
3 answers

Use String#strip to remove all wrapping spaces, or String#chomp (note the 'm') to remove only one trailing newline.

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

I assume that your code did not work, because at the end of the result there were a few lines of new \ whitespace. (And if so, strip will work for you.) However, you can verify this by removing the chop call and then using pu or puts u.inspect to see which characters are in the output.

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

+7
source

str.chomp wll will remove the newline from the lines. str.chop deletes only the last character.

+3
source

Why are you invoking a shell for something so simple:

 h, p1, p2, u = l.split /:/ 
+2
source

Source: https://habr.com/ru/post/897921/


All Articles