Linux Shell脚本攻略学习笔记

时间:2020-12-10 15:39:19

标签(空格分隔): linux shell


命令之乐

  1. cat

    echo 'Text through stdin' | cat - file.txt #-代表标准输入
    cat -s multi_blanks.txt #压缩相邻的空白行
    cat -T file.py # 已^形式显示制表符,方便调试
    cat -n file.txt #显示的同时显示行号
  2. 录制并回放终端会话

    script -t 2> timing.log -a output.session #将时序信息存储到timing.log中,命令信息存储到output.session中
    scriptreplay timing.log output.session #播放录制的命令序列
  3. find命令

    find . -print #打印当前文件和目录的列表
    find /home/slynux -name "*.txt" -print #查找结尾的文件名
    find . \(-name "*.txt" -o -name "*.txt"\) -print #满足多个条件的一个
    find /home/users -path "*/slynux/*" -print #存在包含slynux的路径
    find . -regex ".*\(\.py|\.sh\)$" #正则表达式匹配

    find . -type d -print #列出所有目录
    find . -type f -print
    find . -type f -amin +7 -print #打印出访问时间超过7分钟的文件
    find . -type f -newer file.txt -print #打印出比参考文件更新的所有文件
    find . -type f -size 2M #打印出大于等于2M的所有文件
    find . -type f -name "*.swp" -delete #查找当前目录下所有交换文件,并且删除
    find . -type f ! -perm 644 -print #查找权限设置不是644的文件

    find 配合-exec可以做很多功能

    find . -type f -user root -exec chown xidian {} \; #找到当前文件夹下的属于root的普通文件,并把其ower改为xidian,{}代指匹配到的文件名
    find . -type f -mtime +10 -name "*.txt" -exec cp {} OLD \; #将十分钟前修改的所有txt结尾的文件都保存到OLD目录下
    find . -type f -not -name '*.jpg' -not -name '*.png' \
    -not -name '*.icon' | xargs rm # 删除除了jpg, png icon之外的其他文件,-type f表明在当前目录下删除

    有时候需要排除某些目录,提高查找性能

    find . \(-name "*.git" -prune\) -o \(-type f -print\)
  4. xargs,将从stdin接收到的数据重新格式化,再将其作为参数传递给其他命令

    echo "spleigXhelloXworldX" | xargs -d X # X作为分割符
    cat args.txt | xargs -n 2 ./cecho.sh # 一次性读取两个参数
    car args.txt | xrags -I {} ./cechosh -p {} -l #逐条执行命令并且每一条命令都有参数-p -l

    可以与find结合使用,实现代码行数统计

    find path -type f -name "*.c" -print0|xargs -0 wc -l #统计c代码长度
  5. tr

    echo "HELLO WORL" | tr 'A-Z' 'a-z' #大小写转换
    echo "12345" | tr '0-9' '9876543210'
    echo "hello 123 world 456" | tr -d '0-9' #删除指定的字符集
    echo "hello 123 world 456" | tr -d -c '0-9 \n' #除了指定的字符集,其余都删除
    echo "hello world"|tr -s ' ' #删除重复的空格,只留一个
  6. md5sum

    md5sum file > file_sum.md5 #生成md5校验和
    md5sum -c file_sum.md5 # 进行校验
    类似的sha1sum
  7. sort

    sort -nrk 1 data.txt # 按照第一列数组进行逆序排序
    sort -k 2 data.txt # 按照第二列进行排序
  8. uniq

    sort unsorted.txt | uniq #剔除重复出现的行
    sort unsorted.txt | uniq -u #只显示唯一的行
    sort data.txt | uniq -s 2 -w 2 #忽略前个字符(-s) ,之比较之后的两个字符(-w)
  9. 提取包含扩展名的文件

    file_jpg="sample.jpg"
    name=\$[file_jpg%.\*} # ${VAR%.\*}从VAR中删除位于%右侧的通配符,非贪婪匹配,如果是贪婪的话就变成%%

    和上面相对应的是##匹配 url=”www.google.com”

    echo \${url%.*}
    www.google
    echo \${url%%.*}
    www
    echo \${url#*.}
    google.com
    echo \${url##*.}
    com
  10. rename

    rename 's/ /_/g' * #将文件名里面的空格替换成_

以文件之名

  1. 生成任意文件大小

    dd
    “`
    dd if=/dev/null of=junk.data bs=1M count=1

    ```