首页 » 嵌入式笔记 » 正文

shell 操作集合

正则表达式

  • ^ 表示一行的开头。如:/^#/ 以#开头的匹配。
  • $ 表示一行的结尾。如:/}$/ 以}结尾的匹配。
  • \< 表示词首。 如:\<abc 表示以 abc 为首的詞。
  • \> 表示词尾。 如:abc\> 表示以 abc 結尾的詞。
  • . 表示任何单个字符。
  • * 表示某个字符出现了0次或多次。
  • 字符集合。 如:[abc] 表示匹配a或b或c,还有 [a-zA-Z] 表示匹配所有的26个字符。如果其中有^表示反,如 [^a] 表示非a的字符

读取json变量

#!/bin/sh
# $1:文件名  $2 变量名 注:每个变量必须独占一个行
str=$(grep \"$2\" $1)  #找到变量所在的行 "xx": "ss:x,s",
str=${str#*:}    #裁减掉第一个冒号前所有内容 "ss:x,s",
str=${str#*\"}    #裁减掉第一个双引号前所有内容 ss:x,s",
str=${str%,}     #如果最后一个逗号,则删除 ss:x,s"
str=${str%\"*}    #裁减最后一个双引号后所有内容 ss:x,s
echo $str

字符串替换

#!/bin/sh
# 读取文件
file=/root/config.json
str=$(cat $file)
# 截掉"ip"以前的字符器 xxx“ip": "1.2.3.4"xxxx
str=${str#*\"ip\"}
# 截掉"以前的字符串 变成1.2.3.4"xxxx
str=${str#*\"}
# 截掉"以后所有字符串  %%表示最长的匹配
ip=${str%%\"*}

str=$(cat $file)
str=${str#*\"mac\"}
str=${str#*\"}
mac=${str%%\"*}

str=$(cat $file)
str=${str#*\"gateway\"}
str=${str#*\"}
gateway=${str%%\"*}

echo ip:$ip mac:$mac gateway:$gateway

判断文件

#!/bin/sh
liveFile=liveRtspServer
decoderFile=decoder
filepath=/root/
updatapath=/udisk/
# 判断文件是否存在
checkFile(){
    if [ -e $1 ]; then
        echo "$1 ready"
        return 0
    else 
        echo "$1 not ready"
        return 1
    fi
}
# 判断两个文件是否相同
diffFile(){ 
    diff $1 $2 > /dev/null
    if [ $? == 0 ]; then
        echo "Both file are same"
        return 1
    else
        echo "Both file are different"
        return 0
    fi
}

# 检测
audoUpdata(){
    # 检测U盘里的升级文件
    updataFile="${updatapath}${liveFile}"   
    checkFile $updataFile
    fileReady1=$?
    if [ 1 == $fileReady1 ]; then
        updataFile="${updatapath}${decoderFile}"
        checkFile $updataFile
        fileReady1=$?
        if [ ! 0 == $fileReady1 ]; then
            echo "not find updata file exit.."
            exit 0
        else
            localFile="${filepath}${decoderFile}"
        fi
    else
        localFile="${filepath}${liveFile}"
    fi  

    diffFile $updataFile $localFile
    if [ 0 == $? ]; then
        echo "upgrade file..."
        rm "${filepath}${decoderFile}"
        rm "${filepath}${liveFile}"
        cp $updataFile $filepath
    fi  
}

if [ -e "/dev/sda1" ]; then
#  mount /dev/sda1 /udisk -t vfat
  audoUpdata
  else
  exit 0
fi

发表评论