Wants to echo new line character - ruby

I wants to echo \n like in this way using ruby language:
`echo "array = text.split(/\n/)" > demo`
and demo file should contain output in this way:
array = text.split(/\n/)
But instead to above i am getting in this way, \n produce new line in real which i dont want:
array = text.split(/
/)
Please let me know any options, I already tried backslash and ^ but none of this useful.

If you want to stick with regexps, double-backslash your \n
`echo "array = text.split(/\\n/)" > demo`

You could use split("\n") instead of a regexp.

There are 6 backslash needed here, Like this:
`echo "array = text.split(/\\\\\\n/)" > demo`
This produce excellent results.

Related

How to add a newline in a double quoted string

I have have some code like this:
system("notify-send -i
#{Dir.pwd}/#{file}
#{parsed_songlist["song"][0]['title']}
#{parsed_songlist["song"][0]['artist'].concat("#{parsed_songlist["song"][0]['albumtitle']}")} )
The albumtitle follows the artist name. How can I add a newline between them?
Put "\n" before the string to be added.
Try this :
"\'#{parsed_songlist['song'][0]['title']}\'
\'#{parsed_songlist['song'][0]['artist']}\n#{parsed_songlist['song'][0]['albumtitle']}\'"
The problem in your command is if your title/artist/albumtile contain multi-words like hello hi then in command it will appear as notify-send -i /home/username/file hello hi ...
So you could see how that multi-words 'title' converted as two argumenst for notify-send.
To tackle such problem use \' as I used above.
However, '\n' is enough for adding a newline in a double qouted string.
Here, is what I get when I used above
Use join.
system("notify-send -i
#{Dir.pwd}/#{file}
#{parsed_songlist["song"][0]['title']}
#{ [
parsed_songlist["song"][0]['artist'],
parsed_songlist["song"][0]['albumtitle']
].join("\n") }"
)
I think \n is enough :
"#{parsed_songlist["song"][0]['artist']".concat("\n#{parsed_songlist["song"][0]['albumtitle']")

sed single quotes

I've been banging into escaping single quote's problem using SED (Bash shell).
I need to make
$cfg['Servers'][$i]['password'] = '';
into
$cfg['Servers'][$i]['password'] = 'mypassword';
What I've tried is:
sed -i "s/$cfg['Servers'][$i]['password'] = '';/$cfg['Servers'][$i]['password'] = '$rootpassword';/g" /usr/share/phpmyadmin/libraries/config.default.bak
Which ends up really jumbling the line.
$cfg['Servers'][$i]['password['Servers'][]['passsword'] = 'mypassword'
I've tried the '\'' to escape single quotes and I think everything else under the sun but just can't get it quite there.
can anyone point to my probable obvious mistake?
Thank you.
instead of escaping, you can use \x27 for single quote. this works not only for sed, for awk etc. as well.
see test:
kent$ cat tt
$cfg['Servers'][$i]['password'] = ''
kent$ sed -r 's/(\$cfg\[\x27Servers\x27\]\[\$i\]\[\x27password\x27\] \= \x27)\x27/\1mypassword\x27/g' tt
$cfg['Servers'][$i]['password'] = 'mypassword'
note that, the sed line may not be the best solution for your problem, e.g. put the whole string to "s/../" may not be necessary. However, I just want to show how the \x27 worked.
$ sed -i "s/\$cfg\['Servers'\]\[\$i\]\['password'\] = '';/\$cfg['Servers'][\$i]['password'] = '\$rootpassword';/g" file
Try this:
sed -i "/Servers.*password.*''$/s/''/'foo'/" /path/to/your/testfile
Match a line that contains "anything..Servers..anything..password..anything..''" (end with '') and on that line replace '' with 'foo'
This can match more than one lines, but only the first occurance will be changed.
Test it, it's most probable that .. Servers .. password .. '' is only on one line.
Or you can just escape everything.

How do I strip the characters from this string?

"/home/chief/project/public/system/uploads/000/000/001/original/1/1.flv
to this:
/system/uploads/000/000/001/original/1/1.flv
str = "/home/chief/project/public/system/uploads/000/000/001/original/1/1.flv"
chopped = str.sub(/.*\/public/, "") #=> "/system/uploads/000/000/001/original/1/1.flv"
This will remove everything to the left of public (including /public). This way your code isn't specific to one location, but rather it is more portable in that you can have anything in front of /public, and it will still strip the characters.
s = "/home/chief/project/public/system/uploads/000/000/001/original/1/1.flv"
s.sub("/home/chief/project/public", "")
This should do the trick.
You should specify in which language.
Using sed is trivial.
echo "\"/home/chief/project/public/system/uploads/000/000/001/original/1/1.flv" | sed -e 's-\"/home/chief/project/public--'

how to chop last n bytes of a string in bash string choping?

for example qa_sharutils-2009-04-22-15-20-39, want chop last 20 bytes, and get 'qa_sharutils'.
I know how to do it in sed, but why $A=${A/.\{20\}$/} does not work?
Thanks!
If your string is stored in a variable called $str, then this will get you give you the substring without the last 20 digits in bash
${str:0:${#str} - 20}
basically, string slicing can be done using
${[variableName]:[startIndex]:[length]}
and the length of a string is
${#[variableName]}
EDIT:
solution using sed that works on files:
sed 's/.\{20\}$//' < inputFile
similar to substr('abcdefg', 2-1, 3) in php:
echo 'abcdefg'|tail -c +2|head -c 3
using awk:
echo $str | awk '{print substr($0,1,length($0)-20)}'
or using strings manipulation - echo ${string:position:length}:
echo ${str:0:$((${#str}-20))}
In the ${parameter/pattern/string} syntax in bash, pattern is a path wildcard-style pattern, not a regular expression. In wildcard syntax a dot . is just a literal dot and curly braces are used to match a choice of options (like the pipe | in regular expressions), so that line will simply erase the literal string ".20".
There are several ways to accomplish the basic task.
$ str="qa_sharutils-2009-04-22-15-20-39"
If you want to strip the last 20 characters. This substring selection is zero based:
$ echo ${str::${#str}-20}
qa_sharutils
The "%" and "%%" to strip from the right hand side of the string. For instance, if you want the basename, minus anything that follows the first "-":
$ echo ${str%%-*}
qa_sharutils
only if your last 20 bytes is always date.
$ str="qa_sharutils-2009-04-22-15-20-39"
$ IFS="-"
$ set -- $str
$ echo $1
qa_sharutils
$ unset IFS
or when first dash and beyond are not needed.
$ echo ${str%%-*}
qa_sharutils

How to replace multiple newlines in a row with one newline using Ruby

I have a script written in ruby. I need to remove any duplicate newlines (e.g.)
\n
\n
\n
to
\n
My current attempt worked (or rather not) using
str.gsub!(/\n\n/, "\n")
Which gave me no change to the output. What am I doing wrong?
This works for me:
#!/usr/bin/ruby
$s = "foo\n\n\nbar\nbaz\n\n\nquux";
puts $s
$s.gsub!(/[\n]+/, "\n");
puts $s
Use the more idiomatic String#squeeze instead of gsub.
str = "a\n\n\nb\n\n\n\n\n\nc"
str.squeeze("\n") # => "a\nb\nc"
You need to match more than one newline up to an infinite amount. Your code example will work with just a minor tweak:
str.gsub!(/\n+/, "\n")
For example:
str = "this\n\n\nis\n\n\n\n\na\ntest"
str.gsub!(/\n+/, "\n") # => "this\nis\na\ntest"
are you sure it shouldn't be /\n\n\n/, "\n" that what you seem to be wanting in your question above.
also, are you sure it's not doing a windows new-line "\r\n"?
EDIT: Additional info
Per Comment
"The amount of newlines can change. Different lines have between 2 and 5 newlines."
if you only want to hit the 2-5 lines try this
/\n{2,5}/, "\n"
Simply splitting and recombining the lines will give the desired result
>> "one\ntwo\n\nthree\n".split.join("\n")
=> "one\ntwo\nthree"
Edit: I just noticed this will replace ALL whitespace substrings with newlines, e.g.
>> "one two three\n".split.join("\n")
=> "one\ntwo\nthree"
First check that this is what you want!
Simply calling split will also trim out all of your whitespace.
You need to pass \n to split
>> "one ok \ntwo\n\nthree\n".split(/\n+/).join("\n")
=> "one ok \ntwo\nthree"
Additionally, also works with
spaces on blank lines
n number of back to back blank lines
str.gsub! /\n^\s*\n/, "\n\n"
where,
\n is of course newline
\s is space
denotes 1 or more spaces along when used after \s
Try This It Worked for me:
s = test\n\n\nbar\n\n\nfooo
s.gsub("\n\n", '')
Ruby needs the backslashes escaped differently than you have provided.
str.sub!("\\\\n+\\\\n","\\\\n")
http://www.ruby-forum.com/topic/176239

Resources