我的常用脚本记录
收集一些有用的脚本实例供平时使用,不定期更新。
#!/bin/bash
# 删除当前目录下文件名中包含一些特殊字符的文件
for filename in *
do
#删除文件名包含如下字符的文件:+ { ; " \ = ? ~ ( ) < > & * | $
badname=`echo "$filename" | sed -n /[\+\{\;\"\\\=\?\~\(\)\<\>\&\*\|\$]/p`
rm $badname 2>/dev/null #错误消息将被抛弃
done
# 删除包含空格字符文件名的文件
# find命令匹配到的文件名将被替换到{}的位置
find . -name "* *" -exec rm -f {} \;
exit 0
#!/bin/bash
#拷贝当前目录下所有的文件到指定的另一个目录下
if [-z "$1"]
then
echo "Usage: `basename $0` dir"
exit 1
fi
ls . | xargs -i -t cp ./{} $1
exit 0
#!/bin/bash
#通过名字kill进程
if [ -z "$1" ]
then
"Usage: `basename $0` name"
exit 1
fi
ps -ax | grep "$1" | awk '{print $1}' | xargs -i kill {} 2&>/dev/null
exit $?
#!/bin/bash
#检查指定目录下的脚本文件
FILEHEAD="#!"
if [ $# -gt 2 ]
then
"Usage: `basename $0` [dir]"
exit 1
fi
DIRNAME=$PWD
if [ -n "$1" ]
then
DIRNAME=$1
fi
for file in $DIRNAME/*
do
if [[ -f $file ]] && [[ `head -c2 $file`==$FILEHEAD ]]
then
echo "File \"$file\""
fi
done
exit 0
# -*- coding: utf-8 -*-
'''
python find_str.py [path or file] string
在指定文件,或文件夹下的所有文件中查找含有指定字符串的文件。打印出
包含指定字符串的所有文件名,以及该字符串在相应文件中的行号, 及改行部分内容。
默认是在当前文件下查找。
'''
import os
import sys
parent_path = '.'
target_str = ''
if len(sys.argv) == 1:
exit()
elif len(sys.argv) == 2:
target_str = sys.argv[1]
elif len(sys.argv) == 3:
target_str = sys.argv[2]
parent_path = sys.argv[1]
else:
exit()
def find_str_in_file(filename):
if os.path.isfile(filename):
fread = open(filename, 'r')
lines = fread.readlines()
count = 1
for l in lines:
if l.find(target_str) != -1:
print(filename, 'line:' + str(count), l[0:15])
count = count + 1
elif os.path.isdir(filename):
files = os.listdir(filename)
for f in files:
find_str_in_file(filename + '/' +f)
find_str_in_file(parent_path)
# -*- coding: utf-8 -*-
'''
python img_resize.py path width height
将path文件夹下(默认是当前文件夹)的所有图像,缩放到大小
width*height(默认是640x480)
'''
import os
import sys
import cv2
files = []
imgs = []
width = 640
height = 480
if len(sys.argv) == 1:
files = os.listdir('.')
elif len(sys.argv) == 4:
files = os.listdir(sys.argv[1])
width = int(sys.argv[2])
height = int(sys.argv[3])
else:
print('usage: python img_resize.py path width height')
exit()
img_extend = ['jpg', 'png', 'tiff', 'gif', 'bmp', 'png', 'tga']
for f in files:
if os.path.isfile(f) and f.split('.')[-1].lower() in img_extend:
img = cv2.imread(f)
img = cv2.resize(img, (width, height))
cv2.imwrite(f, img)
参考文档