【shell】一些编程的小技巧及sed(未完成)

来源:互联网 发布:申根签证截止日期 知乎 编辑:程序博客网 时间:2024/05/16 20:31
一. shell的一些常用东东总结
1.计算时间差
  1. time1=$(date +%-'1990-01-01 01:01:01')
  2. echo "time1=$time1"
  3. time2=$(date +%-'1990-01-01 01:01:01')
  4. echo "time2=$time2"
  5. time3=$(($time1+$time2))
  6. echo $time3
2. if then 的写法
  1. if [ "$1" = 'r' ]; then 
  2.     echo "$1" ; exit
  3. fi
if空格[空格arg1空格=空格arg2空格]无空格;空格then
3.通过进程名找到pid,然后kill
android系统中没有pkill,所以只能通过ps找到pid然后kill
  1. pid=`adb shell ps | grep adb | busybox awk '{ print $2 }'
  2. adb shell kill -9 $pid
PC上面:
  1. pid=` ps -ef | grep "adb" | awk '{print $2}' | head -n 1`
  2. kill -9 $pid
4.统计文本文件中单个字符出现的次数
例如统计 hello.txt 中 字符a出现的次数:
  1. grep -'a' hello.txt | wc -l
5. 死循环
  1. while true
  2. do
  3. done
6. 内核中删除未编译的c与其名相同的头文件,对当前目录中的所有文件生效
  1. #!/bin/sh
  2. for c_file in `find . -name "*.c"`
  3. do
  4.     obj_file=`echo "$c_file" | sed 's/\.c/\.o/'`
  5.     if [ ! -"$obj_file" ]; then 
  6.         rm $c_file
  7.         echo "warning: delete c file $c_file"
  8.         head_file=`echo "$c_file" | sed 's/\.c/\.h/'`
  9.         if [ -"$head_file" ]; then 
  10.             rm $head_file
  11.             #echo "the source file is: $c_file"
  12.             echo "warning: delete head file $head_file"
  13.         fi
  14.     fi 
  15. done
注意: 上述脚本只有在内核编译时没有指定out目录,也就是说生成的中间文件与源文件在同一个目录下才有用.
若想只对当前目录生效,则find改为find . -maxdepth 1 -name "*.c"
7. 替换tab为空格
cong@msi:/tmp$ find . -name "*.[hc]" | xargs sed -i 's/\t/    /g'     ;;中间四个空格
vim的配置文件.vimrc中加入:
set expandtab   ;;以后在vi中按tab都成了空格了


二.sed的使用
1. sed的贪婪性
有test.txt想把if的条件去掉
  1. cong@msi:/tmp/test$ cat test.txt 
  2. #define dbg(m) {if (trace_level >= LEVEL_ERROR) TRACE_0(LAYER_DUN, TYPE_ERROR, m);}

如果不管sed的贪婪性,那么匹配就会出现如下问题
  1. cong@msi:/tmp/test$ sed 's/if\ .*)//' test.txt 
  2. #define dbg(m) {;}
正确的
  1. cong@msi:/tmp/test$ sed 's/if\ [^)]*)//' test.txt 
  2. #define dbg(m) { TRACE_0(LAYER_DUN, TYPE_ERROR, m);}
2.删除
a.删除含有cong: video的行
sed -e '/cong: video/!d' log.txt  > 2.txt
b. 删除不包含uart_recv与net_recv的行
sed -r -i  '/uart_recv|net_recv/!d' ./1.txt
    其中 -r, --regexp-extended  : use extended regular expressions in the script.

0 0