1、找出文件sample.txt中出现”Linux”的次数
#!/bin/bash
#how many "Linux" in Linux.txt?
grep -o "Linux" Linux.txt | wc -l
grep -c "Linux" Linux.txt
2、将/etc/passwd的第一列(用户名)取出,以”the n account is $usr”显示每一个用户名。n表示行数,其中,/etc/passwd以”:”作为分隔符
#!/bin/bash
#find the first column of /etc/passwd
awk -F: '{printf("the %d account is %s\n",NR,$1)'} /etc/passwd
{和}前面的'不能用\替换,否则会出错。NR是awk自带的记录数变量。
3、隔行显示文件的内容
#!/bin/bash
#print odd row
cat test.txt | awk '{if (NR%2==1) print $0}'如果要隔行删除这个文件的内容,那么可以把输出重定向,然后删除原文件
4、删除当前目录下非指定日期的文件
#!/bin/sh
ls -1 |while read line
do
month=`echo $line|awk '{print $6}'`
day=`echo $line|awk '{print $7}'
time=echo $line|awk '{print $8}'
file=`echo $linr|awk '{print $9}'
if [ $month="RIGHTMONTH" -a $day="RIGHTDAY" -a $time="RIGHTTIME"
then
continue
else
rm $filr
fi
done这个最好不要轻易尝试,我试了下不小心就把所有脚本文件都删了,在回收站中找不到,应该是进黑洞了,欲哭无泪..
5、挂载/卸载U盘到/mnt/usb
#fidsk -l
#VM->snapshot->找到u盘
#cat /proc/partitions 显示文件系统
cd /mnt
mkdir usb
sudo mount /dev/sdb1 ./usb #挂载
cd usb
ls -l
cd ..
umount ./usb #卸载
6、编写程序,求1+2+3...n的和,要求n从命令行输入
#!/bin/bash
i=1
sum=0
while [ $i -le $1 ]
do
sum=$(($sum+$i))
i=$((i+1))
done
echo "the sum is $sum"
7、设计一个shell程序,输入一个字符串并判断该字符串是不是回文串
#!/bin/bash
#判断输入的字符串是否为回文串,复杂度O(N)
echo "enter string"
read str
len=`echo $str | wc -c`
len=$(($len-1))
l=$(($len/2))
ctr=1
flag=0
while [ $ctr -le $l ]
do
a=`echo $str | cut -c $ctr`
b=`echo $str | cut -c $len`
if [ $a != $b ]
then flag=1
fi
ctr=$(($ctr+1))
len=$(($len-1))
done
if [ $flag -eq 0 ]
then echo "输入的字符串是回文串"
else echo "Are you kidding ? ds,这不是回文串"
fi
本文ZeroClock原创,但可以转载,因为我们是兄弟。