sed之G、H、g、h使用
前言
作者不善言談,如有錯(cuò)誤請(qǐng)指正!!!
轉(zhuǎn)載請(qǐng)注明出處!!!
sed之G、H、g、h使用
什么是sed?
sed是面向流的行編輯器,所謂面向流,是指接受標(biāo)準(zhǔn)輸入的輸入,輸出內(nèi)容到標(biāo)準(zhǔn)輸出上。
sed如何處理數(shù)據(jù)?
sed在正常情況下,將處理的行讀入模式空間(pattern space),腳本中的“sed-command(sed命令)”就一條接著一條進(jìn)行處理,知道腳本執(zhí)行完畢。然后該行唄輸出,模式(pattern space)被清空;接著,在重復(fù)執(zhí)行剛才的動(dòng)作,文件中的新的一行被讀入,直到文件處理完畢。
?
什么是Pattern Space,什么是Hold Space?
pattern space相當(dāng)于車間sed把流內(nèi)容在這里處理。
hold space相當(dāng)于倉(cāng)庫(kù),加工的半成品在這里臨時(shí)儲(chǔ)存。
PS:你可以將pattern space看成是一個(gè)流水線,所有的動(dòng)作都是在“流水線”上執(zhí)行的;而hold space是一個(gè)“倉(cāng)庫(kù)”,“流水線”上的東東都可以放到這里。
為什么要使用sed高級(jí)命令(G、H、g、h、n、N、x)?
由于各種各樣的原因,比如用戶希望在某個(gè)條件下腳本中的某個(gè)命令被執(zhí)行,或者希望模式空間得到保留以便下一次的處理,都有可能使得sed在處理文件的時(shí)候不按照正常的流程來進(jìn)行。這個(gè)時(shí)候,sed設(shè)置了一些高級(jí)命令來滿足用戶的要求。
sed命令:
+ g:[address[,address]]g 將hold space中的內(nèi)容拷貝到pattern space中,原來pattern space里的內(nèi)容清除
+ G:[address[,address]]G 將hold space中的內(nèi)容append到pattern space\n后
+ h:[address[,address]]h 將pattern space中的內(nèi)容拷貝到hold space中,原來的hold space里的內(nèi)容被清除
+ H:[address[,address]]H 將pattern space中的內(nèi)容append到hold space\n后
+ d:[address[,address]]d 刪除pattern中的所有行,并讀入下一新行到pattern中
+ D:[address[,address]]D 刪除multiline pattern中的第一行,不讀入下一行
PS:不論是使用G、g還是H、h,它們都是將hold space里面的內(nèi)容“copy”到pattern space中或者將pattern space中的內(nèi)容“copy”到hold space中。
附上英文的解釋(注意其中的高亮單詞):
The "h" command copies the pattern buffer into the hold buffer. The pattern buffer is unchanged.
Instead of exchanging the hold space with the pattern space, you can copy the hold space to the pattern space with the "g" command. This deletes the pattern space. If you want to append to the pattern space, use the "G" command. This adds a new line to the pattern space, and copies the hold space after the new line.
?
示例:用sed模擬出tac的功能(倒序輸出)。
文件內(nèi)容
cat mm
1
2
3
?
解決方法:
sed ‘1!G;h;$!d’mmps:1!G第1行不 執(zhí)行“G”命令,從第2行開始執(zhí)行。
?????? $!d,最后一行不刪除(保留最后1行)
圖解分析過程
P:Pattern Space
H:Hold Space
藍(lán)色:Hold Space中的數(shù)據(jù)
綠色:Pattern Space中的數(shù)據(jù)
參考:
《sed and awk 第二版》
Sed - An Introduction and Tutorial by Bruce Barnett
sed的高級(jí)應(yīng)用 - haijd Article
轉(zhuǎn)載于:https://www.cnblogs.com/fhefh/archive/2011/11/22/2259097.html
總結(jié)
以上是生活随笔為你收集整理的sed之G、H、g、h使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Visual Studio 清单(man
- 下一篇: SmartDraw_2012_Enter