groovy replace data from file with space - groovy

i want to replace string from a file.
i have a line like this:
qwe{data:"dede-dddd-ssss",login:"user",display:"screen"},abc,xyz
i want to replace all string starting from data to login with spaces
i try this i can only replace the string, is there a way to replace with a starting and endpoint for string?
def source = new File("c:\\sq\\file1.txt")
def dest = new File("c:\\sq\\file2.txt")
def fileText = source.text
def filedest = dest.text
for ( index in 1..9 ) {
fileText = (fileText =~ /data/).replaceFirst("")

This code has an anchored version (to {) of the regex:
def fileText = '''\
qwe{data:"dede-dddd-ssss",login:"user",display:"screen1"},abc,xyz
...
qwe{data:"data2",login:"user2",display:"screen2"},abc,xyz
...
qwe{data:"data3",login:"user3",display:"screen3"},abc,xyz\
'''
fileText = fileText.replaceAll(/(?<=\{)\s*data:[^,]+,\s*login:[^,]+,/ , '')
println fileText
Output:
qwe{display:"screen1"},abc,xyz
...
qwe{display:"screen2"},abc,xyz
...
qwe{display:"screen3"},abc,xyz
Try also in the online groovy web console
UPDATE
If a understand correctly your request: this following code read the input text from source (c:\\sq\\file1.txt) and put the modified text into destination file dest (c:\\sq\\file2.txt):
def source = new File("c:\\sq\\file1.txt")
def dest = new File("c:\\sq\\file2.txt")
dest.write(source.text
.replaceAll(/(?<=\{)\s*data:[^,]+,\s*login:[^,]+,/ , '') )

If you want it in the files, then you can try below, and find the updated data in test2.txt:
note:please update the file paths as per your environment
Courtesy #GsusRecovery for regex
def fileContent = new File('/tmp/test.txt').text
def replacedContent = fileContent.replaceAll(/(?<=\{)\s*data:[^,]+,\s*login:[^,]+,/ , '')
def newFile = new File('/tmp/test2.txt')
newFile.write(replacedContent)

I'm not entirely clear on what your desired outcome is. If you want to remove the "data" and "login" fields and the corresponding values from the input strings, such that your example of:
qwe{data:"dede-dddd-ssss",login:"user",display:"screen"},abc,xyz
becomes:
qwe{display:"screen"},abc,xyz then you can easily use a regex to do this.
The following code:
​String str = """qwe{data:"dede-dddd-ssss",login:"user",display:"screen"},abc,xyz"​​""
str = str.replaceFirst("​​​​​​​​​​​​​data.*login:\".+?\",", '')
println str​
Prints qwe{display:"screen"},abc,xyz

Related

How to replace value in text file with integer? - Groovy (Qupath)

I want to replace a specific value with an integer in a text value. Seems like I am missing something important.
x=5
def file = new File('/Users/path/name.txt')
def newConfig = file.text.replace('abc',x)
file.text = newConfig
tried x.toString() but did not help either.
I am using this code to generate a number, and need that number to be replaced within a .json file.
Thank you
Let's say we have a file with the following string:
testabcandanotherabc
abcandabcandanotherabc
I use the following code:
x = 5
def file = new File('/Users/path/name.txt')
def newConfig = file.text.replaceAll('abc', x.toString())
file.write(newConfig)
It changes the file content as following:
test5andanother5
5and5andanother5
I hope it will help.

groovy input into file iterate over map

Hi I got the map and loop iterate over the map.
def map = [file.txt : file2.txt,
file3.txt : fil4.txt,
file5.txt : file6.txt]
map.each { k,v ->
collection = new file("k").readLines()
collection2 = new file("v").readLines.findResult()
def commons = collection.intersect(collection2)
}
I want every "commons" collection save into a file, not overwriting this file over the next iterations.
Is there a possibility to do such a thing in the loop?
Suppose you already have your list of files to merge, then the only thing you need to do is to write the lines of each file into the output file, you can do something like this:
def files = ['file1.txt', 'file3.txt', 'file2.txt']
def file = new File('output.txt')
def outputFile = file.newPrintWriter()
def mergeFile = { fileName ->
File sourceFile = new File(fileName)
sourceFile.eachLine{ line ->
outputFile.println(line)
}
}
files.each(mergeFile)
out.close()
This will merge the contents of all your files, there is another thing, you may need to specify the folder of the files, so I suggest to use the constructor that receives the folder.
File output = new File(folder, filename)

groovy saving lines from file into collection

Hi I want do save collection from textfile in groovy and save only chosen lines.
I have a file contains that plaintext:
!!file-number1:
!!123.sql
!!123.jpeg
!!333.jpeg
!!texttextext.jpeg
and I want to save it to collection with that result
collection = ['123.jpeg', '333.jpeg', 333.jpeg', 'textextex.jpeg']
Only .jpeg and without "!!"
String filePath = "path/to/file.txt"
File myFile = new File(filePath)
def collection = myFile.collect().retainAll {it == '*.jpeg'}
println collection
And my question is how to remove or ignore things like "!!" and how to print that collection, because i got only output "true".
You can use findResults to "filter" and "map" in one go. e.g.
def lines = """!!file-number1:
!!123.sql
!!123.jpeg
!!333.jpeg
!!texttextext.jpeg"""
println lines.readLines().findResults{ def m = it =~ /!!(.*\.jpeg)/; m ? m[0][1] : null }
// → [123.jpeg, 333.jpeg, texttextext.jpeg]
Or a little bit easier to read, without using the Matcher object:
String filePath = "path/to/file.txt"
def lines = new File(filePath)
.collect()
.findAll { it ==~ /.*jpeg/ }
.collect { it[2..-1] }
println lines
In your example, retainAll() modifies the initial collection and returns a boolean value. See here: https://docs.groovy-lang.org/latest/html/groovy-jdk/java/util/Collection.html

python not removing punctuation

i have a text file i want to remove punctuation and save it as a new file but it is not removing anything any idea why?
code:
def punctuation(string):
punctuations = '''!()-[]{};:'"\,<>./?##$%^&*_~'''
for x in string.lower():
if x in punctuations:
string = string.replace(x, "")
# Print string without punctuation
print(string)
file = open('ir500.txt', 'r+')
file_no_punc = (file.read())
punctuation(l)
with open('ir500_no_punc.txt', 'w') as file:
file.write(file_no_punc)
removing any punctuation why?
def punctuation(string):
punctuations = '''!()-[]{};:'"\,<>./?##$%^&*_~'''
for x in string.lower():
if x in punctuations:
string = string.replace(x, "")
# return string without punctuation
return string
file = open('ir500.txt', 'r+')
file_no_punc = (file.read())
file_no_punc = punctuation(file_no_punc)
with open('ir500_no_punc.txt', 'w') as file:
file.write(file_no_punc)
Explanation:
I changed only punctuation(l) to file_no_punc = punctuation(file_no_punc) and print(string) to return string
1) what is l in punctuation(l) ?
2) you are calling punctuation() - which works correctly - but do not use its return value
3) because it is not currently returning a value, just printing it ;-)
Please note that I made only the minimal change to make it work. You might want to post it to our code review site, to see how it could be improved.
Also, I would recommend that you get a good IDE. In my opinion, you cannot beat PyCharm community edition. Learn how to use the debugger; it is your best friend. Set breakpoints, run the code; it will stop when it hits a breakpoint; you can then examine the values of your variables.
taking out the file reading/writing, you could to remove the punctuation from a string like this:
table = str.maketrans("", "", r"!()-[]{};:'\"\,<>./?##$%^&*_~")
# # or maybe even better
# import string
# table = str.maketrans("", "", string.punctuation)
file_with_punc = r"abc!()-[]{};:'\"\,<>./?##$%^&*_~def"
file_no_punc = file_with_punc.lower().translate(table)
# abcdef
where i use str.maketrans and str.translate.
note that python strings are immutable. there is no way to change a given string; every operation you perform on a string will return a new instance.

How to Read the csv file data one by one and put into variable Using Groovy

Here i am facing One problem that. i want to read the csv file data and one by one put it into a variable and that variable i want to assign a next Http Request let say ids.csv file which consisting of values like this
23333
23334
23335
22336
23336
I am using Jsr223 PreProcessor code:
def csvfile = new File('D:/datas/id/ids.csv')
def lines =csvfile.readLines()
lines.each { String line ->
vars.put('Id_value', line.toString())
}
If it is wrong, how to do this with simple code?
You can emulate JMeter CSV data set which add variables with different suffixes, example in tutorial:
String Filename = vars.get("GETfile");
String fileContents = new File(Filename).getText('UTF-8');
def lines = 0 ;
fileContents.eachLine { line ->
lines++;
vars.put("CSVLine_" + lines, line);
}
vars.put("GETfileLength",lines.toString()) ;
and then loop the variables using ForEach Controller:
You need to add a some form of counter to your JMeter Variables reference names, your current code will create only one Id_value variable with the value of 23336, you need to amend it like:
def csvfile = new File('D:/datas/id/ids.csv')
def lines =csvfile.readLines()
lines.eachWithIndex {line, idx ->
vars.put('Id_value_' + idx, line)
}
And you will get:
Id_value_0=23333
Id_value_1=23334
Id_value_2=23335
Id_value_3=22336
Id_value_4=23336
More information:
Groovy Collection.eachWithIndex()
Groovy is the New Black

Resources