[英]How can I swap two lines using sed?
有沒有人知道如何使用sed編輯器將line a
line b
替換line a
line b
和line b
line a
替換為文本文件中的a line a
?
我可以看到如何用保持空間中的一條線替換模式空間中的一條線(即/^Paco/x
或/^Paco/g
),但是如果我想從Paco
開始的Paco
線怎么辦? Vinh
開頭的線替換它,並從Vinh
開始用線替換它,用從Paco
開始的線替換它?
讓我們假設對於初學者來說, Paco
一條線, Vinh
一條線,並且線條Paco
出現在線Vinh
之前。 然后我們可以轉到一般情況。
#!/bin/sed -f
/^Paco/ {
:notdone
N
s/^\(Paco[^\n]*\)\(\n\([^\n]*\n\)*\)\(Vinh[^\n]*\)$/\4\2\1/
t
bnotdone
}
匹配后/ ^ Paco /我們讀入模式緩沖區直到s //成功(或EOF:模式緩沖區將保持不變)。 然后我們開始搜索/ ^ Paco /。
cat input | tr '\n' 'ç' | sed 's/\(ç__firstline__\)\(ç__secondline__\)/\2\1/g' | tr 'ç' '\n' > output
用您想要的正則__secondline__
替換__firstline__
和__secondline__
。 一定要替換任何實例.
在你的正則表達式[^ç]
。 如果你的文字實際上有ç
,用你的文字沒有的其他東西替換。
GNU sed texinfo doc中的一個簡單示例:
Note that on implementations other than GNU `sed' this script might
easily overflow internal buffers.
#!/usr/bin/sed -nf
# reverse all lines of input, i.e. first line became last, ...
# from the second line, the buffer (which contains all previous lines)
# is *appended* to current line, so, the order will be reversed
1! G
# on the last line we're done -- print everything
$ p
# store everything on the buffer again
h
試試這個awk腳本。
s1="$1"
s2="$2"
awk -vs1="$s1" -vs2="$s2" '
{ a[++d]=$0 }
$0~s1{ h=$0;ind=d}
$0~s2{
a[ind]=$0
for(i=1;i<d;i++ ){ print a[i]}
print h
delete a;d=0;
}
END{ for(i=1;i<=d;i++ ){ print a[i] } }' file
產量
$ cat file
1
2
3
4
5
$ bash test.sh 2 3
1
3
2
4
5
$ bash test.sh 1 4
4
2
3
1
5
使用sed
(或根本不使用)僅用於簡單替換。 更復雜的是,使用編程語言
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.