shell脚本记录

记录工作中常用的几个脚本命令,方便后期查阅。注:以下大部分脚本基于多个同一系统不同文件目录场景。

多个mysql数据库表字段追加指定数值

数据库批量更新指定表字段

#!/bin/bash
db_con="/usr/local/mysql/bin/mysql -uroot -proot"
arr=(db1 db2 db3 db4)
for db in ${arr[*]}
do
    ${db_con} -e "UPDATE ${db}.table SET field=CONCAT(field,',newInsert') WHERE id=1;" 2>/dev/null
    echo ${db} "done"
done

数据表新增字段
${db_con} -e "ALTER TABLE ${db}.table ADD column int UNSIGNED NOT NULL default 0;" 2>/dev/null
注意:追加字段需判断是否已存在该字段,可使用存储过程

批量替换修改多个目录下的文件内容

注意替换数据的唯一性

#!/bin/bash
dir="/home/shell/data/"
arr=(dir1 dir2 dir3)
for f in ${arr[*]}
do
    find ${dir}${f}'/index.html' | xargs sed -i "s/旧数据/替换后的新数据/g"
    echo ${dir}${f}'/index.html done'
done

批量修改文件中的数据

单文件修改,如涉及目录/则可使用#
:%s/oldValue/newValue/g

获取文件匹配的内容数量

:%s/searchKey//gn

删除mysql中excel表格复制的空格

使用replace无法删除excel复制到mysql中的空格,使用字符串删除
update table_name set column = LEFT(column, INSTR(cd_name, '分割的字符')) where id=1;

获取文件修改时间

ll file_check_size.sh --time-style=full-iso|awk '{print $6,$7;}'|sed -e 's/\..*//' -e 's/[- :]//g'

#!/bin/bash
:<<SAY
AUTHOR: IceCry
DESC:useful shell
SAY
exit
dir="/diskb/www/"
db_con="/usr/local/mysql/bin/mysql -uroot -pPassword"
# 数据库名同目录名一致
arr=(wlt_001 wlt_002 wlt_003 wlt_004)
for f in ${arr[*]}
do
    # 文本替换
    find ${dir}${f}'/parentDir/dir/file' | xargs sed -i 's/oldValue/newValue/g'

    # 检测是否开启debug 基于TP
    /bin/cat ${dir}${f}'/index.php' | grep 'APP_DEBUG' | awk -F ',' '{print $2}'

    # 检测文件大小
    /bin/ls -l ${dir}${f}'/dir/file' | awk '{print $5}'

    # 检测文件修改时间
    /bin/ls -l ${dir}${f}'/dir/file' --time-style=full-iso | awk '{print $6,$7;}' | sed -e 's/\..*//' #[-e 's/[- :]//g']

    # 文件复制
    cp -r '/dir/file' ${dir}${f}'/dir/file'

    # 修改数据表
    ${db_con} -e "ALTER TABLE ${f}.table MODIFY cloumn varchar(45) NOT NULL DEFAULT '';" 2>/dev/null

    # 清除数据表缓存
    find ${dir}${f}'/App/Runtime/Data/_fields' | xargs rm -rf

    # 统计指定数据
    ${db_con} -e "SELECT * FROM ${db}.table where (SELECT count(*) FROM ${db}.table2)>2;" >> /diskb/count.txt

    # 更新指定字段数据
    ${db_con} -e "UPDATE ${db}.table SET cloumn=CONCAT(cloumn,',123') WHERE id in (1,2,3);"

    # 新增数据
    ${db_con} -e "INSERT INTO ${db}.table(id, name) values(1, 'tom');"

    echo ${f}' has done'
done

Tags: 运维, shell

仅有一条评论

  1. # 获取文件中指定内容所在行数据(及当前下一行)
    grep -i 'LOG_RECORD' -A 1 ${dir}${f}'/Lawyer/Common/Conf/config.php' | grep -v -e "--" >> log_record.txt

添加新评论