Shell命令之小工具锦集(原创)
在Unix/Linux环境下工作,80%的郁闷都来自于文本处理。
毋庸置疑,Perl很牛很强大,但是,Perl太灵活了,我认可有人说的:Perl程序是那种写完一个小时之后,连自己都读不懂的程序。
来看看Shell吧,简洁就是美!
1. 替换当前目录下,所有XML后缀名文件里的某个单词
find ./ -name '*.xml' -exec sed -i 's/AWord/Bword/' {} \;
2. 去掉讨厌的^M,从Windows复制到Linux的文本文件,每一行后面都有这个东西
sed -i 's/\r//g' test.txt
3. awk和sed合作
ll *.man | awk '{print $8}' | sed 's/\.man//g' > test.txt
4. 重定向,stdout和stderr
ls >test1.txt 2> test2.txt
5. 统计行数
# count together find . -name "*.py" | xargs cat | grep -v ^$ | wc -l # count seperater find . -name "*.py" -exec wc -l {} \;6. eval的用法
v=aaa; bb="bbbbbbbbbb"; eval $v='$bb'; echo aaa:$aaa7. 优雅的awk
ls -al | awk -F - '!/^xxxx/{printf "%s --> %s\n", $7, $3}' ls -al | awk '/sepiaipsevents\./{x=x+$5}END{print x}'
8. 近乎神奇的shell变量
# % means pattern from the end, min for x in `find ./ -name "*.txt"`;do echo $x ${x%.*};done # %% means pattern from the end, max for x in `find ./ -name "*.txt"`;do echo $x ${x%%.*};done # # means pattern from the begin, min for x in `find ./ -name "*.txt"`;do echo $x ${x#/*/};done # ## means pattern from the begin, max for x in `find ./ -name "*.txt"`;do echo $x ${x##/*/};done # {#x} means the length of the variable for x in `find ./ -name "*.txt"`;do echo $x ${#x};done # {replace} x="shuaigeliusiyeshuaige";y=${x/shuaige/cuonan};echo $y; x="shuaigeliusiyeshuaige";y=${x//shuaige/cuonan};echo $y; # {if null} x="shuaigeliusiyeshuaige";y=${x:-notnull};echo $y;