sed
-i
: is used to affect the file.
^
: is a beginning of line
- $ : is a end of line
d
: delete if there is a empty line
((.|\n)*)
: multiple line
刪除含有FOO及BAR這兩個字串的行
sed "s/^.*FOO.*BAR.*$//g" fstab
這作法該行被刪除,但是會是空的一行
改成 :
sed "/^.*FOO.*BAR.*$/d" file.txt
該行被刪除,不會變成空行
去除空行
sed -i "/^\s*$/d" file.txt
取代空白
\s*
取代 windows 換行
sed -i 's/\r$//' wrap-trim.log
修改檔案內容
假設有一個test檔:
$a = 'ccc';
$b = 'ddd';
$c = 'ccc';
$d = 'fff';
將取代結果印出,但還不會做取代的動作
$ sed "s/'ccc'/'QQQ'/g" test
$a = 'QQQ';
$b = 'ddd';
$c = 'QQQ';
$d = 'fff';
取代檔案內容
sed -i "s/'ccc'/'QQQ'/g" test
取代檔案內容, 還會建一個原始檔案的輩份檔(.bak, 可自訂SUFFIX)
sed -i.bak "s/'ccc'/'QQQ'/g" test
test.bak 為原始檔案的輩份 ; test 為取代後的檔案
執行多個取代
sed -e "s/line1/line3/g" -e"s/line2/line4/g" /tmp/q.txt
使用-e
串在後面
-e script, –expression=script : add the script to the commands to be executed
-i[SUFFIX], –in-place[=SUFFIX] : edit files in place (makes backup if extension supplied)
sed: -e expression #1, char 26: extra characters after command :
注意脫逸字元
-e script, –expression=script : add the script to the commands to be executed
取代資料夾下所有檔案的取代的字串(recursive)
find . -type f -print0 | xargs -0 sed -i 's/from/to/g'
取得指定行數的區間, 並輸出成一個新檔案
sed -n 5870,5900p handler.log > /tmp/tmp.log
awk
預設以空白
分隔
df | grep "/dev/loop" | awk '{print $2}'
以 %
分隔
df | grep "/dev/loop" | awk -F "%" '{print $2}'
print要用單引號括起來`
, 不能用雙引號"
找出 lengh > 200 的行
awk 'length>200' common.log