- 正則表達式
正則解決:#符合IP基本格式篩選
基礎正則: grep
擴展正則:egrep
- 字符限定符類
- 點· 表示匹配任意一個字符 -----------> abc. 可以匹配 abc9 abcd
- [ ]可以匹配[ ]d裏面的任意一個----> [abc]t 可以匹配at,bt,ct
- – 匹配字符串的範圍 ---------------> [0-9]
- [[:xxx:]]grep預定義的一些命令字符,[[:alpha:]]匹配一個字母,[[:digit:]]匹配一個數字
- ^位於[ ]括號內的開頭 ,匹配括號中字符以外的任意一個字符
因此[ ^xy ]匹配除了xy以外的任一個字符[^xy]o可以匹配ao,bo…
2.數量限定符
1. ?:表示緊跟在他前面單元應該匹配零次或者一次
[0-9]?\.[0-9]匹配0,2.3,等,因爲.在正則表達式中有自己的含義因此需要用\轉義一下篩選出小數點
2. +:緊跟在他前面的單元匹配一次或者多次
3. *:表示緊跟在前面匹配0次或者多次
4.(n)
-sed用法
//在第三行後面添加hello
sed '3ahello' 1.txt;
//在有123後面添加hello
sed '/123/ahello' 1.txt;
//文本最後一行添加hello
sed '$ahello' 1.txt
//在第三行之前插入hello
sed '3ihello' 1.txt;
sed '/123/ihello/' 1.txt;
sed '$ihello' 1.txt
//將第一行更改成爲hello;
sed '1chello' 1.txt
//將包含123的內容更改成爲hello
sed '/123/chello' 1.txt
//將最後一行替換成爲hello
sed '$chello' 1.txt
//刪除第四行內容
sed '4d' 1.txt
//從第一行開始刪除,每隔2行就刪除一行
sed '1~2d' 1.txt
//刪除1-2行
sed '1,2d' 1.txt
//刪除1-2行之外的所有行
sed '1,2!d' 1.txt
//刪除最後一行
sed '$d' 1.txt
//刪除包含123的行
sed '/123/d' 1.txt
//刪除包含123的所有行
sed '/123/,d' 1.txt
//刪除空行
sed '/^$/d' 1.txt
//刪除不匹配123或者abc的行
sed '/123\|abc/!d' 1.txt
//刪除1-3行中匹配123或abc的行
sed '1,3{/123\|abc/d}' 1.txt
//將文件中的123替換成hello默認之替換第一個
sed 's/123/hello/' 1.txt
//文本中所有都替換
sed 's/123/hello/g' 1.txt
//將每行中第二個123替換
sed 's/123/hello/2' 1.txt
//將每一行中匹配的123替換成hello
//並且將替換內容寫入2.txt中
sed -n 's/123/hello/gpw 2.txt' 1.txt
//匹配所有的#的行,替換行中逗號的所有內容爲空,(,.*)
//表示逗號後面所有內容爲空
sed '/#/s/,.*//g' 1.txt
//將最後一行的兩個字符替換爲空
sed 's/..$//g' 1.txt
//匹配#號後面所有的內容爲空
sed 's/^#.*//g' 1.txt
//先替換1.txt文件中所有註釋行爲空行
//然後刪除空行,刪除和替換用;分隔開來
sed 's/^#.*//;/^$/d' 1.txt
//在每一行後面加上“hahah"
sed 's/$/&'haha'/' 1.txt
----------打印問價中的行-------------------
//打印文件中第三行
sed -n '3p' 1.txt
//從第二行開始每隔離兩行打印一行
sed -n '2~2p' 1.txt
//打印最後一行
sed -n '$p' 1.txt
//打印1-3行
sed -n '1,3p' 1.txt
//打印從匹配too行到最後一行的內容
sed -n '/too/,+1p' 1.txt
//打印從boo到too內容
sed -n '/boo/,/too/' 1.txt
//打印文件的行號
sed -n '$=' 1.txt
//打印匹配到error的行號
sed -n '/eror/=' 1.txt
//打印匹配到error的行號和內容
sed -n '/error/{=;p}' 1.txt
//將文件內容讀取出來讀入1.txt
sed 'r 2.txt' 1.txt
//在1.txt第三行之後插入2.txt 的文件內容
sed '3r 2.txt' 1.txt
//在1.txt 中123 內容後面插入2.txt的文件內容
sed '/245/r 2.txt' 1.txt
-----------------向文件中寫入內容--------------------------
//將1.txt中第二行的內容寫入文件中
sed -n '2w 2.txt' 1.txt
//將1.txt的第一行和最後一行分別寫入1.txt和3.txt中
sed -n -e '1w 2.txt' -e '$w 3.txt' 1.txt
-----------------sed在shell腳本中的使用--------------------------
#替換文件內容
#!/bin/bash
if [ $# -ne 3 ];then
echo "Usage: $0 oldpart new-part filenam"
return
fi
sed -i "s#$1#$2#" $3
#刪除文件中的空白行
#!/bin/bash
if [ ! -f $1];then
echo "$0 is not a file"
exit
fi
sed -i "/^$/d" $1
#批量更改當前目錄中的文件後綴名字
#!/bin/bash
for i in [$1]; do
if [ -f $i ]; then
iname=`basename $i` #獲取文件名
newname=`echo $iname | sed -e "s/$1/$2/g"`
mv $iname $newname
fi
done