Statistics
| Revision:

root / tmp / org.txm.groovy.core / src / groovy / org / txm / sw / SearchReplaceInDirectory.groovy @ 479

History | View | Annotate | Download (2.4 kB)

1
package org.txm.sw
2
// Copyright © - ENS de Lyon - http://textometrie.ens-lyon.fr
3
// @author sheiden
4
//
5
// This file is part of the TXM platform.
6
//
7
// The TXM platform is free software: you can redistribute it and/or modify
8
// it under the terms of the GNU General Public License as published by
9
// the Free Software Foundation, either version 3 of the License, or
10
// (at your option) any later version.
11
//
12
// The TXM platform is distributed in the hope that it will be useful,
13
// but WITHOUT ANY WARRANTY; without even the implied warranty of
14
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
// GNU General Public License for more details.
16
//
17
// You should have received a copy of the GNU General Public License
18
// along with the TXM platform.  If not, see <http://www.gnu.org/licenses/>.
19
//
20
// $LastChangedDate: 2013-05-02 11:28:42 +0200 (jeu. 02 mai 2013) $
21
// $LastChangedRevision: 2378 $
22
// $LastChangedBy: sheiden $
23
//
24

    
25
// parameters
26

    
27
// **change this parameter**
28
dir = new File(System.getProperty("user.home"), "Bureau/voeux")
29

    
30
// **change this parameter**
31
ext = "\\.txt"
32

    
33
// **change this parameter**
34
find = ""
35

    
36
// **change this parameter**
37
replaceWith = "'"
38

    
39
// **change this parameter**
40
encoding = "utf-8"
41

    
42
// **change this parameter**
43
// 'true' = only display matching lines, 'false' = replace in matching files
44
showMatchingFilesOnly = false
45

    
46

    
47
//find = /date="([0-9]+)-([0-9]+-[0-9]+)"/
48
                      // **change this parameter**
49
//replaceWith = 'date="$1-$2" year="$1"'
50
                      // **change this parameter** (warning: '$1', '$2'... can be interpreted by Groovy in "..." strings)
51

    
52
// main body
53
println "in $dir ... "+/.*$ext/
54
dir.eachFileMatch(~/.*$ext/) { file ->               // for each file matching extension
55
        println file.getName()
56
        
57
if (showMatchingFilesOnly) {
58
        
59
       file.eachLine(encoding) { line ->                  // for each line
60
           if (line.matches(".*$find.*")) { println " *match* : "+line }
61
           }
62
} else {
63
       def tmp = File.createTempFile("SearchReplaceInDirectoryTemp", ".tmp", dir) // create temporary file
64
       tmp.write('')                                // create empty file
65
       tmp.withWriter(encoding) { writer ->
66
           file.eachLine(encoding) { line ->                  // for each line
67
                   writer.println line.replaceAll(find, replaceWith) // find&replace and print
68
           }
69
       }
70
       file.delete()
71
       tmp.renameTo(file)                           // save results
72
 }
73
}