shell programming sheat sheet for myself

语法总是记不牢,文字记录之,搞个cheat sheet,自己用。。

1. 数值计算
a=0; (( a = a +1 )); echo $a

2. for循环
for f in `ls`; do echo $f; done

3. while循环
a=0; while [ $a -lt 10 ]; do echo -n "$a "; (( a = a+1 )); sleep 1; done ; echo;
a=0; while (( a < 10 )); do echo -n "$a "; (( a = a +1 )); sleep 1; done ; echo;

4. if判断
if [ -d /usr/local/bin ] ; then echo "directory exists."; else echo "directory not exists."; fi
if test -d /usr/local/bin; then echo "directory exists."; else echo "directory not exists."; fi
[ -d /usr/local/bin ] && echo "directory exists"
[ -d /user/local/bin ] || echo "directory not exists"

# for integers
num1 -eq num2 True if num1 equals num2.
num1 -ne num2 True if num1 is not equal to num2.
num1 -lt num2 True if num1 is less than num2.
num1 -gt num2 True if num1 is greater than num2.
num1 -le num2 True if num1 is less than or equal to num2.
num1 -ge num2 True if num1 is greater than or equal to num2.

# for string
str1 = str2 True if str1 and str2 are identical.
str1 != str2 True if str1 and str2 are not identical.
-n str1 True if str1 is not null (length is greater than zero).
-z str1 True if str1 is null (length is zero).

# for file conditions
-f somefile True if somefile exists and is an ordinary file.
-d somefile True if somefile exists and is a directory.
-s somefile True if somefile contains data (the size is not zero).
-r somefile True if somefile is readable.
-w somefile True if somefile is writable.
-x somefile True if somefile is executable.

# logical operators
cond1 -a cond2 True if both cond1 and cond2 are true.
cond1 -o cond2 True if either cond1 or cond2 is true.
! cond1 True if cond1 is false.


5. sed
sed 's/one/two/g' < in.file.txt > out.file.txt
sed -r 's/[0-9]{3,}//g' < in.file.txt  <-- 注1
sed 's:old:new:g' < in.file.text > out.file.txt <-- 注2
sed -r 's/[0-9]{3,}/(&)/g' < sed.txt
sed -r 's/([0-9]+)\s+([a-z]+)/\2 \1/g' < sed.txt <-- 注3
sed -n -r '/\S+/p' < sed.txt <-- 注4
sed -r '/^$/d' < sed.txt
sed -n -r 's/([0-9]+)\s+([a-z]+)/\2 \1/gpw test.txt' < sed.txt <-- 注5
sed -r -e 's/([0-9]+)\s+([a-z]+)/\2 \1/g' -e '/^$/d' < sed.txt  <--注6

注1: -r参数启用extended regular expression,原来自带的太弱了,而且要记好几套正则表达式很烦,干脆只要用到正则表达式的地方都启用扩展的,比如grep -E "[0-9]+"
注2: 分割符号可以是 / , :  ,  _ , |
注3: 如果不启用-re那么'('还得写成'\(',很恶心
注4: sed默认会打印每一行(不论有没匹配),-n表示默认不打印,后面的p表示如果匹配了那执行打印该行,整行意思是打印非空的行
注5: /p 答应 /g 全局 /w file 结果写到文件,可以组合多个command
注6: 多条sed指令用-e分开

你可能感兴趣的:(programming)