首页 > 代码库 > sed && awk 第二章runsed代码理解
sed && awk 第二章runsed代码理解
#! /bin/sh 2 for x 3 do 4 echo "editing $x: \c" 5 # if test "$x"=sedscr; then 6 # echo "not editing sedscript!" 7 if [ "$x" = "sedscr" ];then 8 echo "bi not editing sedscript!" 9 elif test -s $x;then 10 echo "x exist " 11 sed -f sedscr $x > /tmp/$x$$ 12 if test -s /tmp/$x$$ 13 then 14 if cmp -s $x /tmp/$x$$ 15 then 16 echo "file not changed:\c" 17 else 18 mv $x $x.bak 19 cp /tmp/$x$$ $x 20 fi 21 echo "done" 22 else 23 echo "sed produced an empty file\c" 24 echo " - check your sedscript." 25 fi 26 rm -f /tmp/$x$$ 27 else 28 echo "original file is empty." 29 fi
这个代码有三个地方不理解,现在终于理解了
1.for x
当时不了解这种结构,后面google,找到一个文档。http://www.thegeekstuff.com/2011/07/bash-for-loop-examples/?utm_source=feedburner。 就是for 不接 in的时候,自动会将位置变量 存入到其中
3. Don’t specify the list; get it from the positional parameters
If you don’t specify the keyword “in” followed by any list of values in the bash for loop, it will use the positional parameters (i.e the arguments that are passed to the shell script).
$ cat for3.sh i=1 for day do echo "Weekday $((i++)) : $day" done $ ./for3.sh Mon Tue Wed Thu Fri Weekday 1 : Mon Weekday 2 : Tue Weekday 3 : Wed Weekday 4 : Thu Weekday 5 : Fri
Caution: Please be careful if you use this method. You should not include the keyword “in” in the for loop. If you leave the keyword “in” without any values, it will not use the positional parameter as shown below. It will not go inside the loop. i.e for loop will never get executed as shown in the example below.
$ cat for3-wrong.sh i=1 for day in do echo "Weekday $((i++)) : $day" done $ ./for3-wrong.sh Mon Tue Wed Thu Fri
2.第二点在自己linux上敲的时候,代码逻辑跟想的不一样。后面才发现 shell 中 [ $a = ‘abcd‘ ] 有严格空格要求,中间只能用=号,跟python 混淆了。在变量跟括号之间要各有空格。 在变量与变量之间也要有空格,可以参考https://stackoverflow.com/questions/4277665/how-do-i-compare-two-string-variables-in-an-if-statement-in-bash
sed && awk 第二章runsed代码理解
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。