Delete row in text file - groovy

I'm reading a text file in Groovy:
new File(testprojectDir + '/Testdata///' + filename).withReader('UTF-8') { reader ->
def line
while ((line = reader.readLine()) != null) {
log.info "${line}"
}
}
The text file generates as follows:
123
456
789
My problem Is that I'd like to remove the line I've just red.
Example: 123 will be deleteted after it's been red.
And continue to next row, read that line and remove that line (save the same text file) until the file no longer has rows, that means that the text file is empty (every line is deleted)
How can I do that?

You can use an output file.
def ofile = new File(outputFile)
new File(testprojectDir + '/Testdata///' + filename).withReader('UTF-8') { reader ->
def line
while ((line = reader.readLine()) != null && !line.contains("text i don't want")) {
log.info "${line}"
ofile.append(line)
}
}
If you want to do it in-place:
def fileA = new File("src/file.txt")
List data = fileA.readLines()
fileA.text = ''
data.each { line ->
if (!line.contains("b")) {
log.info "${line}"
fileA.append(line) + "\n"
}
}

Related

Change only the numbers of a line in a file

I would like to change only the numbers of a line.
Source file:
IMAGE_VERSION_TD_S=1.108.1.1
IMAGE_VERSION_CPO=1.87.13.1
IMAGE_VERSION_CVM=1.71.1.1
I would like to search for a string like ("IMAGE_VERSION_CPO=") and change only the numbers to 1.90.12.1.
Output file:
IMAGE_VERSION_TD_S=1.108.1.1
IMAGE_VERSION_CPO=1.90.12.1
IMAGE_VERSION_CVM=1.71.1.1
I have tried on this way but it generated a new line on the final file:
def data = readFile(file: pathEnv)
def lines = data.readLines()
def strNewEnv = ''
lines.each {
String line ->
if (line.startsWith("IMAGE_VERSION_CPO=")) {
strNewEnv = strNewEnv + '\n' + 'IMAGE_VERSION_CPO=' + imageVersion
} else {
strNewEnv = strNewEnv + '\n' + line
}
println line
}
println strNewEnv
writeFile file: directoryPortal+"/${params.ENVIROMENT}/"+envFile, text: strNewEnv
If this is a properties file, use the readProperties step:
def props = readProperties file: pathEnv, text: "IMAGE_VERSION_CPO=${imageVersion}"
writeFile file: "${directoryPortal}/${params.ENVIROMENT}/${envFile}", text: props.collect { "${it.key}=${it.value}" }.join("\n")
If, for some reason, this isn't a props file:
def data = readFile(file: pathEnv)
data = data.replaceAll(/(?<=IMAGE_VERSION_CPO=)[\d\.]+/, imageVersion)
writeFile file: "${directoryPortal}/${params.ENVIROMENT}/${envFile}", text: data
There's likely a much better regex for that but it seems to be working

How to check all files in a directory except one file in Groovy language

I am trying to search a word in every file in a directory but I want to exclude my logfile.
My code is something like this
user input: search test C:\Users\Desktop\test\Groovy
My code
import static groovy.io.FileType.FILES
import java.text.SimpleDateFormat
def terminal_log = new File("terminal.log")
def terminal_log_path = terminal_log.getName()
def fas = ""
def file2_path = ""
def cmd = System.console().readLine 'Enter command: '
String[] csplice = cmd.split(" ");
if(csplice.length == 3){
def first_parameter = csplice[0]
def second_parameter = csplice[1]
def third_parameter = csplice[2]
if(first_parameter == "search"){
def file = new File(third_parameter)
if(file.exists()){
if(file.isDirectory()){
file.eachFile(FILES) { f ->
fas = "/"+f+"/"
File file2 = new File(fas)
file2_path = file2.getName()
if(!file2_path == terminal_log_path){
file2.eachLine{ line ->
if(line.contains(second_parameter)){
println "This file contains this word"
}
}
}
}
}else{
println "Not a directory"
}
}else{
println "Not exists"
}
}else{
println "Invalid command"
}
}else{
println "Invalid command"
}
This block here is not working
if(!file2_path == terminal_log_path){
Is there any documentation that I can read to exclude a specific file while checking every files in a directory?
Many thanks
EDIT:
the directory of the user input has the logfile (terminal.log)
terminal.log exists
It should be:
if (file2_path != terminal_log_path) {
...
}
or
if (!(file2_path == terminal_log_path)) {
...
}
E.g. you can run the following code to see the result of applying the "Not" operator to a string in Groovy:
def file2_path = "/i/am/path/"
println (!file2_path) // prints false as file2_path is not an empty string
For more info, you can refer to the official Groovy doc on that topic:
The "not" operator is represented with an exclamation mark (!) and inverts the result of the underlying boolean expression. In particular, it is possible to combine the not operator with the Groovy truth:
assert (!true) == false
assert (!'foo') == false
assert (!'') == true

how to fix expecting anything but ''\n''; got it anyway

I have the following line in my code
def genList = (args[]?.size() >=4)?args[3]: "
when I run my whole code I get the following error
expecting anything but ''\n''; got it anyway at line: 9, column: 113
here I am adding the whole code so you can see what I am doing
def copyAndReplaceText(source, dest, targetText, replaceText){
dest.write(source.text.replaceAll(targetText, replaceText))
}
def dire = new File(args[0])
def genList = (args[]?.size() >=4)?args[3]: " // check here if argument 4 is provided, and generate output if so
def outputList = ""
dire.eachFile {
if (it.isFile()) {
println it.canonicalPath
// TODO 1: copy source file to *.bak file
copy = { File src,File dest->
def input = src.newDataInputStream()
def output = dest.newDataOutputStream()
output << input
input.close()
output.close()
}
//File srcFile = new File(args[0])
//File destFile = new File(args[1])
//File srcFile = new File('/geretd/resume.txt')
//File destFile = new File('/geretd/resumebak.txt')
File srcFile = it
File destFile = newFile(srcFile + '~')
copy(srcFile,destFile)
// search and replace to temporary file named xxxx~, old text with new text. TODO 2: modify copyAndReplaceText to take 4 parameters.
if( copyAndReplaceText(it, it+"~", args[1], args[2]) ) {
// TODO 3: remove old file (it)
it.delete()
// TODO 4: rename temporary file (it+"~") to (it)
// If file was modified and parameter 4 was provided, add modified file name (it) to list
if (genList != null) {
// add modified name to list
outputList += it + "\n\r"
}
}
}
}
// TODO 5: if outputList is not empty (""), generate to required file (args[3])
if (outputList != ""){
def outPut = new File(genList)
outPut.write(outputList)
}
Thank you
Just close your double quotes
def genList = (args?.size() >=4)?args[3]: ""
The specific OP question was already answered, but for those who came across similar error messages in Groovy, like:
expecting anything but '\n'; got it anyway
expecting '"', found '\n'
It could be caused due to multi-line GString ${content} in the script, which should be quoted with triple quotes (single or double):
''' ${content} ''' or """ ${content} """
Why do you have a single " at the end of this line: def genList = (args[]?.size() >=4)?args[3]: "?
You need to make it: def genList = (args[]?.size() >=4)?args[3]: ""
You need to add a ; token at the end of def outputList = ""
Also get rid of the " at the end of def genList = (args[]?.size() >=4)?args[3]: "

how to replace a string/word in a text file in groovy

Hello I am using groovy 2.1.5 and I have to write a code which show the contens/files of a directory with a given path then it makes a backup of the file and replace a word/string from the file.
here is the code I have used to try to replace a word in the file selected
String contents = new File( '/geretd/resume.txt' ).getText( 'UTF-8' )
contents = contents.replaceAll( 'visa', 'viva' )
also here is my complete code if anyone would like to modify it in a more efficient way, I will appreciate it since I am learning.
def dir = new File('/geretd')
dir.eachFile {
if (it.isFile()) {
println it.canonicalPath
}
}
copy = { File src,File dest->
def input = src.newDataInputStream()
def output = dest.newDataOutputStream()
output << input
input.close()
output.close()
}
//File srcFile = new File(args[0])
//File destFile = new File(args[1])
File srcFile = new File('/geretd/resume.txt')
File destFile = new File('/geretd/resumebak.txt')
copy(srcFile,destFile)
x = " "
println x
def dire = new File('/geretd')
dir.eachFile {
if (it.isFile()) {
println it.canonicalPath
}
}
String contents = new File( '/geretd/resume.txt' ).getText( 'UTF-8' )
contents = contents.replaceAll( 'visa', 'viva' )
As with nearly everything Groovy, AntBuilder is the easiest route:
ant.replace(file: "myFile", token: "NEEDLE", value: "replacement")
As an alternative to loading the whole file into memory, you could do each line in turn
new File( 'destination.txt' ).withWriter { w ->
new File( 'source.txt' ).eachLine { line ->
w << line.replaceAll( 'World', 'World!!!' ) + System.getProperty("line.separator")
}
}
Of course this (and dmahapatro's answer) rely on the words you are replacing not spanning across lines
I use this code to replace port 8080 to ${port.http} directly in certain file:
def file = new File('deploy/tomcat/conf/server.xml')
def newConfig = file.text.replace('8080', '${port.http}')
file.text = newConfig
The first string reads a line of the file into variable. The second string performs a replace. The third string writes a variable into file.
Answers that use "File" objects are good and quick, but usually cause following error that of course can be avoided but at the cost of loosen security:
Scripts not permitted to use new java.io.File java.lang.String.
Administrators can decide whether to approve or reject this signature.
This solution avoids all problems presented above:
String filenew = readFile('dir/myfile.yml').replaceAll('xxx','YYY')
writeFile file:'dir/myfile2.yml', text: filenew
Refer this answer where patterns are replaced. The same principle can be used to replace strings.
Sample
def copyAndReplaceText(source, dest, Closure replaceText){
dest.write(replaceText(source.text))
}
def source = new File('source.txt') //Hello World
def dest = new File('dest.txt') //blank
copyAndReplaceText(source, dest) {
it.replaceAll('World', 'World!!!!!')
}
assert 'Hello World' == source.text
assert 'Hello World!!!!!' == dest.text
other simple solution would be following closure:
def replace = { File source, String toSearch, String replacement ->
source.write(source.text.replaceAll(toSearch, replacement))
}

words count example in Scala?

I see a lot of Scala tutorials with examples doing things like recrursive traversals or solving math problems. In my daily programming life I have the feeling most of my coding time is spent on mundane tasks like string manipulation, database queries and date manipulations. Is anyone interested to give an example of the a Scala version of the following perl script?
#!/usr/bin/perl
use strict;
#opens a file with on each line one word and counts the number of occurrences
# of each word, case insensitive
print "Enter the name of your file, ie myfile.txt:\n";
my $val = <STDIN>;
chomp ($val);
open (HNDL, "$val") || die "wrong filename";
my %count = ();
while ($val = <HNDL>)
{
chomp($val);
$count{lc $val}++;
}
close (HNDL);
print "Number of instances found of:\n";
foreach my $word (sort keys %count) {
print "$word\t: " . $count{$word} . " \n";
}
In summary:
ask for a filename
read the file (contains 1 word per line)
do away with line ends ( cr, lf or crlf)
lowercase the word
increment count of the word
print out each word, sorted alphabetically, and its count
TIA
A simple word count like that could be written as follows:
import io.Source
import java.io.FileNotFoundException
object WC {
def main(args: Array[String]) {
println("Enter the name of your file, ie myfile.txt:")
val fileName = readLine
val words = try {
Source.fromFile(fileName).getLines.toSeq.map(_.toLowerCase.trim)
} catch {
case e: FileNotFoundException =>
sys.error("No file named %s found".format(fileName))
}
val counts = words.groupBy(identity).mapValues(_.size)
println("Number of instances found of:")
for((word, count) <- counts) println("%s\t%d".format(word, count))
}
}
If you're going for concise/compact, you can in 2.10:
// Opens a file with one word on each line and counts
// the number of occurrences of each word (case-insensitive)
object WordCount extends App {
println("Enter the name of your file, e.g. myfile.txt: ")
val lines = util.Try{ io.Source.fromFile(readLine).getLines().toSeq } getOrElse
{ sys.error("Wrong filename.") }
println("Number of instances found of:")
lines.map(_.trim.toLowerCase).toSeq.groupBy(identity).toSeq.
map{ case (w,ws) => s"$w\t: ${ws.size}" }.sorted.foreach(println)
}
val lines : List[String] = List("this is line one" , "this is line 2", "this is line three")
val linesConcat : String = lines.foldRight("")( (a , b) => a + " "+ b)
linesConcat.split(" ").groupBy(identity).toList.foreach(p => println(p._1+","+p._2.size))
prints :
this,3
is,3
three,1
line,3
2,1
one,1

Resources