linux script 技巧 / tips

  • 参考

文件名操作

获取扩展名

https://stackoverflow.com/a/2352397

1
file_ext=$(echo $filename |awk -F . '{if (NF>1) {print $NF}}')

Loop Through Files In A Directory

https://www.cyberciti.biz/faq/unix-loop-through-files-in-a-directory/

1
2
3
4
5
for file in $*
do
 # do something on $file
 [ -f "$file" ] && cat "$file"
done

批量重命名

1
2
# 文件夹批量重命名
for f in */; do mv ${f%%/} ${f%%/}.git; done

Bash remove leading / trailing

1
2
# The syntax is to remove leading whitespaces:
${var##*( )}
1
2
3
4
5
6
7
8
9
10
# Just remove leading whiltespace
#turn it on
shopt -s extglob
 
output="    This is a test"
output="${output##*( )}"
echo "=${output}="
 
# turn it off
shopt -u extglob
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# To trim leading and trailing whitespace using bash
#turn it on
shopt -s extglob
output="    This is a test    "
 
### Trim leading whitespaces ###
output="${output##*( )}"
 
### trim trailing whitespaces  ##
output="${output%%*( )}
echo "=${output}="
 
# turn it off
shopt -u extglob