TCL 脚本实例: 从文件中删除字符串

 

1)在linux 系统下, 输入tclsh进入 tcl模式

2)source filename (执行当前程序的文件名,你可以自己起)

3)用法:delete  pattern?  path?

e.g.  假如一个目录中有很多文件,我想删除所有以b开头的文件中含有 “FSGUIProv” 的字符串。我们可以这么用 delete "FSGUIProvl" ~quickz/draft/b*

参数一为任何你想删除的字符串,参数二为模式匹配文件,可以指定具体文件,也可以任何其他模式。

 

在当前文件夹下会产生一个小log文件,存在delete.log中

 

### 判断文件中是否含有需要删除的字符串

proc checkpat {pattern filename} {
        set ret 0
        set f [open $filename r+]
        while {[gets $f line] >= 0} {
                set ret1 [regexp $pattern $line]
                if {$ret1 == 1 } {
                    set ret 1
                    return yes
                }
        }
        if {$ret == 0} {return no}
        close $f
 
}


### delete pattern1 in the files at PATH
proc delete {pattern {path "*" }} {
             set flag 0
             set flag1 0
             set flag2 0
             set filelist [glob $path]
             set log [open delete.log a+]
             foreach filename $filelist {
                     incr flag
                     ### Check the necessity of accessing to the filename
                     set retpat [checkpat $pattern  $filename]
                     puts "$flag,$filename: $retpat"
                     ### delete pattern of folders in path
       if {$retpat == "yes"} {
                          incr flag1
                          set f [open $filename r+]
                          set nf [open $filename.tmp w+]
                          while {[gets $f line] >= 0} {
                                if {[regsub -all $pattern $line "" newline]} {
                                        puts $nf $newline
                                } else {puts $nf $line}
                          }
                          flush $f;close $f
                          flush $nf;close $nf
                          file rename -force $filename.tmp $filename
                     } else {
                             incr flag2
                       }
 
             }
             puts $log "/n[exec date]"
             puts $log "Total: $flag, deleted: $flag1"
             puts $log "Seraching file pattern: $path"
             flush $log
             close $log
}
### Log file will be created in local directory

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值