Replace double backslashes with single backslash using JS223 processor - jmeter

I have a variable (CONTEXTTOKEN) which I extract in JMeter using a Boundary Extractor. This variable has double backslashes as below:
I am using a JS223 processor to try and replace the double backslashes with a single one like this:
def myVariable = vars.get("CONTEXTTOKEN")
def request = myVariable.replaceAll("\\", "\")
vars.put("CONTEXTTOKEN", request)
However when I run my script CONTEXTTOKEN still has double backslashes

Ok I resolved this by doing a .toString().replace("\\\\","\\").

Related

How to split a string by slash in ruby

how can i split a string "DESKTOP-AHDESI\Username" by slash in ruby 2.7.1p83
tmp = "DESKTOP-AHDESI\Username"
print tmp
tmp = tmp.split("\\")
print tmp
i got:
Ruby Error: NoMethodError undefined method `gsub!'
Problem
Your tmp variable is enclosed in double-quotes, and contains a backslash which is being interpreted as an escape rather than a character literal. You can see this easily by simply pasting your string into a REPL like irb:
"DESKTOP-AHDESI\Username" #=> "DESKTOP-AHDESIUsername"
You need to handle the backslash specially in both your String methods.
Solution
One way to handle this is to use Ruby's alternate quoting mechanism. For example:
%q(DESKTOP-AHDESI\Username).split '\\' #=> ["DESKTOP-AHDESI", "Username"]
This may not help you directly, though.
Wherever the value from tmp is coming from, you need to refactor the code to ensure that your String is properly escaped before you assign it to your variable, or otherwise pre-process it. String#dump won't really help much if the value you're assigning is unescaped before assignment, so you're going to have to fix this in whatever code you're using to generate or grab the string in the first place.
First of all, you are giving the wrong string. \ is the escape character when you use inside the "". So It will try to escape the next character U but this character doesn't have any Job so it will print U on the screen. Modify your string like below, it will work.
tmp = "DESKTOP-AHDESI\\Username"
p tmp
tmp = tmp.split("\\")
p tmp
Output
"DESKTOP-AHDESI\\Username"
["DESKTOP-AHDESI", "Username"]

Create a shell-escaped POSIX path in macOS

I need to create a string from a full POSIX path (starting at the root), so that it could be pasted directly into a Unix shell like bash, e.g. in Terminal.app, without the need for quotes around the path.
(I do not actually pass the string to a shell, but instead need it for passing it to another program. That program expects the path in just the form that you get when you drag a file into Terminal.app.)
For that, I need to escape at least any spaces in the string, by prepending them with a backslash. And some more characters as well.
For example, this path:
/directory/-as"<>' *+
Would be escaped as follows:
/directory/-as\"\<\>\'\ \*+
What's a safe algorithm to perform that conversion? I could escape every character, but that would be overkill.
There seems to be no framework function for doing this, so I'll need to do the replacing with string operations.
To be conservative (for the most popular shells), while also avoiding clearly unnecessary escapings, what set of characters should be escaped?
For the record, Terminal.app escapes the following non-control ASCII chars when dropping a file name into its window:
Space
!"#$%&'()*,:;<=>?[]`{|}~
And these are not escaped:
Control codes (00-1F and 7F)
Alphanumerical
+-.#^_
And here's the code that would perform the replacement:
NSString* shellPathFromPOSIXPath (NSString *path)
{
static NSRegularExpression *regex = nil;
if (!regex) {
NSString *pattern =
#"([ !\\\"\\#\\$\\%\\&\\'\\(\\)\\*\\,\\:\\;\\<\\=\\>\\?\\[\\]\\`\\{\\|\\}\\~])";
regex =
[NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
}
NSString *result =
[regex stringByReplacingMatchesInString:path
options:0
range:NSMakeRange(0, path.length)
withTemplate:#"\\\\$1"];
return result;
}
Better to put the whole thing in single quotes, rather than adding backslashes to individual characters; then the only character you need to escape is a single-quote present inside the string.
The Python standard library's implementation, provided as an example which can be easily reimplemented in any other language having only basic primitives, reads as follows:
def quote(s):
"""Return a shell-escaped version of the string *s*."""
if not s:
return "''"
if _find_unsafe(s) is None:
return s
# use single quotes, and put single quotes into double quotes
# the string $'b is then quoted as '$'"'"'b'
return "'" + s.replace("'", "'\"'\"'") + "'"
That is to say, the general algorithm is as follows:
An empty string becomes '' (a pair of literal single-quotes).
A string which is known to be safe (though it's safest to not try to implement a codepath for this at all, particularly as shells often implement their own syntax extensions in undefined space) can be emitted bare/unquoted.
Otherwise, prepend a ', emit your input string with all 's replaced with the literal string '"'"', and then append a final '.
That's it. You don't need to escape backslashes (they're literal inside single quotes), newlines (likewise), or anything else.

CSV generates multiple double quote in string of ruby

I use ruby to generate a CSV file. One of my data is a string which contain a double quote "in it, for example ="000123".
This is my code:
csv = CSV.generate do |csv|
csv << ["=\"000123\""]
end
However, it will generate a wrong string with additional double quote:
2.4.0 :005 > puts csv
"=""000123"""
What I expect result is ="000123". Does anyone know the reason? How to solve this?
That's actually how CSV escapes double quotes:
If double-quotes are used to enclose fields, then a double-quote
appearing inside a field must be escaped by preceding it with
another double quote. For example:
"aaa","b""bb","ccc"
and because your field has double quotes inside it, you are required to quote the entire column:
Each field may or may not be enclosed in double quotes (however
some programs, such as Microsoft Excel, do not use double quotes
at all). If fields are not enclosed with double quotes, then
double quotes may not appear inside the fields.
(emphasis mine) If you really want to disable that feature though, just set the quote_char to something else:
puts CSV.generate(quote_char: "'") { |csv| csv << ["=\"000123\""] }
# ="000123"

Unable to substitute escaped characters in string

I have this string:
str = "no,\"contact_last_name\",\"token\""
=> "no,\"contact_last_name\",\"token\""
I want to remove the escaped double quoted string character \". I use gsub:
result = str.gsub('\\"','')
=> "no,\"contact_last_name\",\"token\""
It appears that the string has not substituted the double quote escape characters in the string.
Why am I trying to do this? I have this csv file:
no,"contact_last_name","token",company,urbanization,sec-"property_address","property_address",city-state-zip,ase,oel,presorttrayid,presortdate,imbno,encodedimbno,fca,"property_city","property_state","property_zip"
1,MARIE A JEANTY,1083123,,,,17 SW 6TH AVE,DANIA BEACH FL 33004-3260,Electronic Service Requested,,T00215,12/14/2016,00-314-901373799-105112-33004-3260-17,TATTTADTATTDDDTTFDDFATFTDDDTTFADTTDFAAADDATDAATTFDTDFTTAFFTTATFFF,017,DANIA BEACH,FL, 33004-3260
When I try to open it with CSV, I get the following error:
CSV.foreach(path, headers: true) do |row|
end
CSV::MalformedCSVError: Illegal quoting in line 1.
Once I removed those double quoted strings in the first row (the header), the error went away. So I am trying to remove those double quoted strings before I run it through CSV:
file = File.open "file.csv"
contents = file.read
"no,\"contact_last_name\",\"token\" ... "
contents.gsub!('\\"','')
So again my question is why is gsub not removing the specified characters? Note that this actuall does work:
contents.gsub /"/, ""
as if the string is ignoring the \ character.
There is no escaped double quote in this string:
"no,\"contact_last_name\",\"token\""
The interpreter recognizes the text above as a string because it is enclosed in double quotes. And because of the same reason, the double quotes embedded in the string must be escaped; otherwise they signal the end of the string.
The enclosing double quote characters are part of the language, not part of the string. The use of backslash (\) as an escape character is also the language's way to put inside a string characters that otherwise have special meaning (double quotes f.e.).
The actual string stored in the str variable is:
no,"contact_last_name","token"
You can check this for yourself if you tell the interpreter to put the string on screen (puts str).
To answer the issue from the question's title, all your efforts to substitute escaped characters string were in vain just because the string doesn't contain the character sequences you tried to find and replace.
And the actual problem is that the CSV file is malformed. The 6th value on the first row (sec-"property_address") doesn't follow the format of a correctly encoded CSV file.
It should read either sec-property_address or "sec-property_address"; i.e. the value should be either not enclosed in quotes at all or completely enclosed in quotes. Having it partially enclosed in quotes confuses the Ruby's CSV parser.
The string looks fine; You're not understanding what you're seeing. Meditate on this:
"no,\"contact_last_name\",\"token\"" # => "no,\"contact_last_name\",\"token\""
'no,"contact_last_name","token"' # => "no,\"contact_last_name\",\"token\""
%q[no,"contact_last_name","token"] # => "no,\"contact_last_name\",\"token\""
%Q#no,"contact_last_name","token"# # => "no,\"contact_last_name\",\"token\""
When looking at a string that is delimited by double-quotes, it's necessary to escape certain characters, such as embedded double-quotes. Ruby, along with many other languages, has multiple ways of defining a string to remove that need.

Ruby quotes, why am I seeing triple double quotes when I save this CSV to a file?

I am using FastCSV.
WHen I do this:
title = "\"" + some_title + "\""
My file looks like:
"""some title """, 23, 22
I want:
"some title", 23,22
My guess would be that fastercsv is adding the extra quotes to escape the quotes in your input string.
So if you're input string is [Hello, CSV], faster csv would have to enclose it within double quotes so that csv parsing isn't disrupted by the comma. Ditto for double quotes which have significance in CSV.
I'd say try sending string without the quotes, let fastercsv decide when it needs the double quotes OR use single quotes like Jacob suggests.

Resources