shell训练营Day26

练习71

  1. 判断所给目录内哪些二级目录下有没有text.txt文件。
  2. 有text.txt文件的二级目录,计算出该test.txt文件里面所给出单词的次数。
  3. 假如脚本名字为1.sh, 运行脚本的格式为 ./1.sh 123 root,其中123为目录名字,而root为要计算数量的单词。

#!/bin/bash

if [ $# -ne 2 ]
then
echo "请提供两个参数,第一个参数是目录名字,第二个参数是单词"
exit
fi

cd $1
for f in ls .
do
if [ -d $f ]
then
if [ -f $f/test.txt ]
then
n=grep -cw "$2" $f/test.txt
echo "$1/$f目录下面有test.txt, 该test.txt里面的有$n个$2."
fi
fi
done

练习72
交互式脚本,根据提示,需要用户输入一个数字作为参数,最终打印出一个正方形。在这里我提供一个linux下面的特殊字符■,可以直接打印出来。

示例: 如果用户输入数字为5,则最终显示的效果为

■ ■ ■ ■ ■
■ ■ ■ ■ ■
■ ■ ■ ■ ■
■ ■ ■ ■ ■
■ ■ ■ ■ ■

#!/bin/bash

while :
do
read -p "Please input a nuber: " n
n1=echo $n|sed 's/[0-9]//g'
if [ -n "$n1" ]
then
echo "$n is not a nuber."
continue
else
break
fi
done

for i in seq 1 $n
do
for j in seq 1 $n
do
echo -n "■ "
done
echo
done

练习73
写一个脚本,依次向/etc/passwd中的每个用户问好,并且说出对方的ID是什么,如:

Hello, root,your UID is 0.

#!/bin/bash
cat /etc/passwd |while read line
do
username=echo $line|awk -F ':' '{print $1}'
uid=echo $line|awk -F ':' '{print $3}'
echo "Hello, $username, your uid is $uid."
done

练习74
linux系统 /home目录下有一个文件test.xml,内容如下:

<configuration>
    <artifactItems>
        <artifactItem>
       <groupId>zzz</groupId>
       <artifactId>aaa</artifactId>
    </artifactItem>
    <artifactItem>
       <groupId>xxx</groupId>
       <artifactId>yyy</artifactId>
    </artifactItem>
    <!-- </artifactItem><groupId>some groupId</groupId>
       <version>1.0.1.2.333.555</version> </artifactItem>-->
    </artifactItems>
</configuration>

请写出shell脚本删除文件中的注释部分内容,获取文件中所有artifactItem的内容,并用如下格式逐行输出:
artifactItem:groupId:artifactId:aaa

#!/bin/bash

sed '/<!--.-->/d' test.xml > test2.xml
egrep -n '<!--|-->' test2.xml |awk -F ':' '{print $1}' > /tmp/line_number1.txt
n=wc -l /tmp/line_number1.txt|awk '{print $1}'
n1=$[$n/2]
for i in seq 1 $n1
do
j=$[$i
2]
k=$[$j-1]
x=sed -n "$k"p /tmp/line_number1.txt
y=sed -n "$j"p /tmp/line_number1.txt
sed -i "$x,$y"d test2.xml
done

grep -n 'artifactItem>' test2.xml |awk '{print $1}' |sed 's/://' > /tmp/line_number2.txt
n2=wc -l /tmp/line_number2.txt|awk '{print $1}'

get_value(){
sed -n "$1,$2"p test2.xml|awk -F '<' '{print $2}'|awk -F '>' '{print $1,$2}' > /tmp/value.txt

cat /tmp/value.txt|while read line
do
    x=`echo $line|awk '{print $1}'`
    y=`echo $line|awk '{print $2}'`
    echo artifactItem:$x:$y
done

}

n3=$[$n2/2]
for j in seq 1 $n3
do
m1=$[$j2-1]
m2=$[$j
2]
nu1=sed -n "$m1"p /tmp/line_number2.txt
nu2=sed -n "$m2"p /tmp/line_number2.txt
nu3=$[$nu1+1]
nu4=$[$nu2-1]
get_value $nu3 $nu4
done

练习75
请撰写一个shell函数,函数名为 f_judge,实现以下功能

  1. 当/home/log目录存在时将/home目录下所有tmp开头的文件或目录移到/home/log目录。

  2. 当/home/log目录不存在时,创建该目录,然后退出。

#!/bin/bash

f_judge()
{
if [ -d /home/log ]
then
find /home -name "tmp*" -exec mv {} /home/log/ \;
else
mkdir /home/log
exit
fi
}
f_judge

猜你喜欢

转载自blog.51cto.com/12898947/2345269