linux复习2(shell脚本)

1. 编写shell脚本,逆序打印一行文本,如输入“welcome”,则输出为“emoclew”。

  1 read -p "Please input a String: " str
  2 len=${#str}                                                                            
  3 for((i=$len-1;i>=0;i--))        
  4 do         
  5     echo -e  "${str:$i:1}\c"    
  6 done       
  7 echo ""   

易错总结

1.read -p str 会将输入字符串打印出来
2.$ {#str} str字符串的长度
3.注意字符串str 最后一个数的索引为$len-1
4. {str: x :y} 读取字符串第x位开始数的y位
5.echo “” 作为字符串的结束符
6.echo -e " \c" 表示不换行读取

2. 编写shell脚本,将目录test1、test2、test3中的文件a1、a2、a3文件,改名为aa1、aa2、aa3。

1 mv test1/a1 test1/aa1
2 mv test2/a2 test2/aa2
3 mv test3/a3 test3/aa3      

易错总结

1.mv 文件名1 文件名2
2.当文件不在同一个目录下时,要指定对应的文件名
3.路径采用的是/ ,而不是\

3. 编写shell脚本,将当前目录下大于8K的文件转移到/tmp/file目录下。

  1 size=$[1024*8]                      
  2                                     
  3 for file in $(ls -l |awk '$5 > $size {print $9 }')                                     
  4 do                                  
  5     mv $file tmp/file               
  6 done                                
  7 echo Finshed                        
  8                                     
  9 ls -la  tmp/file 

易错总结

1.shell脚本中数据的计算 $[1024*8]
2.awk后面使用单引号
3.awk’$5 > $size { print $9 }’ awk中$5表示文件大小 $9表示文件名称
4.注意 $ 与()连用,而不是{}
5.显示某一目录下的文件 ls -la tmp/file

4. 编写shell脚本,把当前目录下所有后缀为“.sh”的文件后缀变更为“.shell” 。

  1 old=sh                      
  2 new=shell                   
  3 dir=$(eval pwd)             
  4 for file in $(ls $dir| grep  .${old})
  5 do                          
  6     name=$(ls ${file} | cut  -d. -f1)
  7     mv $file  ${name}.${new}                                                           
  8 done                        
  9 echo "Finshed"    

易错总结

1. ( e v a l p w d ) 2. g r e p . (eval pwd) 切换到执行命令的目录 2.grep . {old} 挑选对应后缀名的文件
3. ls $ dir 显示目录下所有的文件
4. 当字符串中存在除$ 以外其他的字符时,要使用$ { }
5.cut -d. f1 表示取以.为分隔符的第一个字段
6.当存在多个$ 内外嵌套时,外面使用() 里面使用{}
7.出现替换错误的原因使用错误 $应该匹配{ }
8.为了防止结束符错误,在程序的结尾加上echo " "

5. 编写shell脚本,把当前目录(包含子目录)下所有后缀为“.txt”的文件后缀变更为“.doc” 。

  1 function getdir ()
  2 {      
  3     for element in `ls $1`
  4     do 
  5         file_or_dir=$1"/"$element
  6         if [ -d $file_or_dir ];then
  7             getdir $file_or_dir
  8         else 
  9             if [ ${element##*.} = "txt" ];then
 10                 base=${file_or_dir%.txt}
 11                 mv $file_or_dir  ${base}.$new
 12             fi
 13         fi
 14     done
 15 }      
 16        
 17        
 18 old=txt                                                                                
 19 new=doc
 20        
 21 dir=$(eval pwd) 
 22        
 23 getdir $dir  

易错总结

1.路径使用的是/,而不是
2.KaTeX parse error: Expected '}', got '#' at position 9: {element#̲#*.} 表示文件名后缀 3.…{file_or_dir%.txt} 表示去掉字符串.txt后缀
5.注意`ls $1`等价于 $(ls $1)

发布了122 篇原创文章 · 获赞 221 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/jjsjsjjdj/article/details/103490463