這是Linux課程的幾則Shell編程學習札記。
1、找出檔案sample.txt中出現"Linux"的次數
#!/bin/bash
#how many "Linux" in Linux.txt?
grep -o "Linux" Linux.txt | wc -l
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 $line | awk '{print $9}'`
if [ $month="RIGHTMONTH" -a $day="RIGHTDAY" -a $time="RIGHTTIME" ]
then
continue
else
rm $file
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 #卸載