开发者

sed or awk to move one chunk of text betwen first pattern pair into second pair?

I need to process a text file. Need to move the chunk of text between the first pattern pair into the second pattern pair (above whatever was already there between the second pattern pair.

Sample input:

...many lines of text
[pattern]
chunk of text
text I开发者_StackOverflow中文版 need to move
[/pattern]
...more lines of text
[pattern]
something here or empty
[/pattern]
...more lines of text

Indended output:

...many lines of text
[pattern]
[/pattern]
...more lines of text
[pattern]
chunk of text
text I need to move
something here or empty
[/pattern]
...more lines of text

Is there any sed or awk command that can do that? I searched all over the Net and could not get it working. Thank you!


#!/usr/bin/awk -f

/\[pattern\]/ {
    flag = 1
    count++
    print
    next
}

flag == 1 && count == 2 {
    print accum
    accum = ""
    flag = 0
}

/\[\/pattern\]/ {flag = 0}

flag == 0 {print}
flag == 1 && count == 1 {
    accum = accum delim $0
    delim = RS
}


Ruby(1.9+)

#!/usr/bin/env ruby

data=File.open("file").read
puts data.gsub(/(.[^\]]*\[pattern\])(.[^\[]*)(\[\/pattern\])(.[^\]]*\[pattern\])(.*)\z/m , "\\1\n\\3\\4\\2\\5" )

test run

$ cat file    
1 2 3
[pattern]
chunk of text
text I need to move
[/pattern]
4 5 6
[pattern]
something here or empty
[/pattern]
7 8 9    
[pattern]
blah blah
[/pattern]

$ ruby script.rb    
1 2 3
[pattern]
[/pattern]
4 5 6
[pattern]
chunk of text
text I need to move

something here or empty
[/pattern]
7 8 9    
[pattern]
blah blah
[/pattern]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜