Linux Shell脚本攻略学习笔记

来源:互联网 发布:同花顺交易软件安装 编辑:程序博客网 时间:2024/04/25 23:42

标签(空格分隔): 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 -printfind . -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.googleecho \${url%%.*}wwwecho \${url#*.}google.comecho \${url##*.}com
  10. rename

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

以文件之名

  1. 生成任意文件大小

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

    ```
0 0