转载

Shell脚本实例

fileopen命令实现

fileopen命令是为了实现Mac系统下,在终端中用应用打开文件。

首先将目录 /Users/huanghuan/Work/MyCMD 命令加入环境变量中,Mac下可配置在 /etc/bashrc 中。然后创建 fileopen 文件,其内容为:

 1 #! /bin/sh  2 if [ $# != 2 ]  3 then  4     echo "输入参数错误!"  5 else  6    search_result=`find /Applications -maxdepth 1  -name *${1}*.app | wc -l`  7    app_list=`find /Applications -maxdepth 1  -name *${1}*.app`  8    if (($search_result<=0))  9    then 10        echo "未找到对应程序" 11    elif (($search_result==1)) 12    then 13        echo "打开文件" 14        open ${app_list} ${2} 15    else 16        echo "符合条件的程序有:/n${app_list}" 17        echo "请重新输入正确的程序名" 18    fi 19 fi 20 exit 

命令的运行效果如下:

Shell脚本实例

PS:该命令将进一步完善,目前作为一个Shell练习而简单实现

todo命令实现

todo命令实际上就是实现了一个toDoList的小命令,配置如fileopen命令,其内容为:

 1 #! /bin/sh  2  3 path="/Users/huanghuan/Work/MyCMD/toDoList"  4  5 while getopts a:r: option  6 do  7   case $option in  8        a)  9          echo ${OPTARG}" 创建时间:"`date +%Y年-%m月-%d日` >>$path 10          ;; 11        r) 12          if [ -f "$path" ] 13          then 14              gsed -i "${OPTARG}d" $path 15          fi 16          ;; 17        ?) 18          echo "Usage: toDo [-arp] [arg]" 19          echo "-a add todo item" 20          echo "-r remove todo item" 21          echo "-p print todo List" 22          exit 23          ;; 24   esac 25 done 26 27 echo "当前待办项目:" 28 if [ -f "$path" ] 29 then 30     cat -n $path 31 fi 32 exit 

命令的运行效果如下:

Shell脚本实例

该命令的扩展参见: todo扩展

Valid Phone Numbers

来源于Leetcode题目: Valid Phone Numbers

Given a text file file.txt that contains list of phone numbers (one per line), write a one liner bash script to print all valid phone numbers.

You may assume that a valid phone number must appear in one of the following two formats: (xxx) xxx-xxxx or xxx-xxx-xxxx. (x means a digit)

You may also assume each line in the text file must not contain leading or trailing white spaces.

For example, assume that file.txt has the following content:

987-123-4567 123 456 7890 (123) 456-7890 

Your script should output the following valid phone numbers:

987-123-4567 (123) 456-7890 

脚本代码:

grep -E '^([0-9]{3}-|/([0-9]{3}/) )[0-9]{3}-[0-9]{4}$' file.txt 

使用 -E 可以少写很多转义字符,这道题还值得注意的是: what’s the difference between /d and [0-9] in grep

原文  http://sadwxqezc.github.io/HuangHuanBlog/shell/2016/03/30/Shell脚本实例.html
正文到此结束
Loading...