Chinaunix首页 | 论坛 | 博客
  • 博客访问: 116607
  • 博文数量: 24
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 0
  • 用 户 组: 普通用户
  • 注册时间: 2016-11-22 14:58
个人简介

坚持,做最好的自己

文章分类

全部博文(24)

文章存档

2015年(2)

2014年(9)

2013年(13)

我的朋友

分类: LINUX

2013-04-02 17:44:33

#!/bin/ksh
#将当前目录及子目录中的jsp文件增加字符集设置、修改include的相对路径
f_time=0
for jspfile in `find . -name "*.jsp" | grep -v '/bak/' `
do
  f_time=`expr $f_time + 1`     #记录文件个数
  #修改include


  #除去Include文件,其他包含Include.jsp的文件
  if [ `echo $jspfile |grep Include | wc -l` -eq 0 -a `cat $jspfile |grep "Include.jsp" | wc -l` -ne 0 ]
  then
    includer='\<%@ include file=\"'`echo $jspfile | tr -d "[:alnum:]" | sed -e s'/\.//g' -e 's/\//..\\\\\//g' -e 's/_//g' | cut -c2-`'Include.jsp\" %\>'
    v_time=0                      #记录文件行数
    cat $jspfile |
    while read line
    do
      v_time=`expr $v_time + 1`
      if [  `echo "$line" | grep "Include.jsp" | wc -l` -ne 0 ]
      then
        cat $jspfile | grep -v "Include.jsp" | sed "${v_time}i${includer}" > $jspfile.3
        mv $jspfile.3 $jspfile
        echo $f_time:$jspfile:include:html:$v_time
        break
      fi


    done
  fi


  if [ `cat $jspfile | grep -i "contentType=" | grep -i "charset=" | wc -l ` -eq 0 ]
  then
    inserter='\<%@ page contentType=\"text\/html; charset=gb2312\" %\>'
    v_time=0                      #记录文件行数
    cat $jspfile |
    while read line
    do
      v_time=`expr $v_time + 1`
      if [  `echo "$line" | grep -i "" | wc -l` -ne 0 ]
      then
        cat $jspfile | sed "${v_time}s/<[Hh][Tt][Mm][Ll]>/${inserter}\n&/" > $jspfile.1
        mv $jspfile.1 $jspfile
        echo $f_time:$jspfile:insert:html:$v_time
        break
      fi


      if [  `echo "$line" | grep "<%" | wc -l` -ne 0 ]
      then
        cat $jspfile | sed "${v_time}s/<%/${inserter}\n&/" > $jspfile.2
        mv $jspfile.2 $jspfile
        echo $f_time:$jspfile:insert:"<%":$v_time
        break
      fi


    done
  fi


done
------------------------------------------------------------
调试中发现,sed命令在执行的过程中会发生卡死,原因为jsp文件中有特殊字符。可以使用grep -v 进行过滤
由于只能在第一处特定字符处插入字符串,程序中使用循环的方式进行指定,比较傻,可以使用grep -n 然后cut -d: -f1的方式指定
另外sed的版本不能过低,本例使用的版本是GNU sed version 4.1.5

上文使用循环找到指定行再替换的方式有点愚蠢。
完全可以使用更简单的方式,比如,在第一次出现task字符串的前一行插入fast
在linux环境可以使用

点击(此处)折叠或打开

  1. sed '/task/{s//fast\n&/;:1;n;b1}'
  2. sed ':a;N;$!ba;s/task/fast\n&/'
  3. sed '0,/task/s//fast\n&/'
  4. sed '0,/task/{s/task/fast\n&/}'
在两种环境下都可以使用awk实现

点击(此处)折叠或打开

  1. awk '/task/&&T<1{$0="fast\n"$0;T++}1'
  2. awk '/task/&&!a++{printf "fast\n"}1'







阅读(1575) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~