Linux趣事 -- (1)shell腳本

本文是用shell腳本解決三道題目,分別爲:
(1)將/etc/passwd的第一列(用戶名)取出,以”the n account is $usr”顯示每一個用戶名。n表示行數,其中,/etc/passwd以”:”作爲分隔符。
(2)找出文件sample.txt中單詞”Linux” 出現的次數。
(3)在當前目錄下有一個文本文件test.txt,每隔一行就有一行亂碼。如何做到隔行刪除?

第一題(三種解法)

解法一:
#!/bin/bash   
echo "$(awk -F ":" '{print "The " NR " account is " $1}' /etc/passwd)"

注意點:
(1)http://xpleaf.blog.51cto.com/9315560/1678565
(2)http://www.linuxidc.com/Linux/2013-01/77225.htm

解法二:
#!/bin/bash
row=`cat /etc/passwd | wc -l`
for i in `seq 1 $row`
do
    user=`sed -n "$i"p /etc/passwd | awk -F ':' '{print $1}'`
    echo "This $i account is "$user""
done

注意點:
(1)鍵盤第二排第一個鍵 `
(2)有兩處是數字 1 , 分別爲seq處和print處。
(3)http://blog.csdn.net/wjplearning/article/details/77981715

解法三:
#!/bin/bash
accounts=`cat /etc/passwd | cut -d':' -f1`
for account in $accounts
do
    declare -i i=$i+1
    echo "The $i account is \"$account\""
done

注意點:
(1)http://www.runoob.com/linux/linux-comm-declare.html
(2)http://blog.csdn.net/tangy110/article/details/6278259
(3)http://blog.csdn.net/qianqin_2014/article/details/52200172
(4)http://3y.uu456.com/bp_8x8pd7x9bt0wekt4q3cr_3.html

第二題

#!/bin/bash                                                                                                                     
grep -o "Linux" sample.txt | wc -l

注意點:
(1)http://www.linuxidc.com/Linux/2013-01/77225.htm

第三題(奇偶解法)

刪除奇數行
#!/bin/bash
awk 'NR % 2==0' test.txt
或 sed '1~2d' test.txt
刪除偶數行
#!/bin/bash
awk 'NR%2==1' test.txt
或 sed '1~2!d' test.txt

注意點:
(1)http://blog.csdn.net/mengxianhua/article/details/22732677
(2)http://www.kuqin.com/article/24shell/15807.html
(3)http://blog.csdn.net/mengxianhua/article/details/22732677

注:注意點裏還有些其它的寫法,可以去看一看。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章