我想知道如何更改文件中一行的位置(最好使用sed).例如,考虑包含的文件
goal identifier statement
let statement 1
let statement 2
forall statement
other statements
Run Code Online (Sandbox Code Playgroud)
我希望能够做到这一点
goal identifier statement
forall statement
let statement 1
let statement 2
other statements
Run Code Online (Sandbox Code Playgroud)
我改变了forall线的位置并将其带到了球门线后面.forall和goal是可用于识别线条的正则表达式.
你可以尝试,为移动line 4到line 2,我想移动line A到line B,其中A>B
sed -n '2{h; :a; n; 4{p;x;bb}; H; ba}; :b; p' file
Run Code Online (Sandbox Code Playgroud)
要么 A<B
sed -n '2{h; d}; 4{p; x;}; p' file
Run Code Online (Sandbox Code Playgroud)
你得到,在第一种情况下:移动line 4到line 2
goal identifier statement
forall statement
let statement 1
let statement 2
other statements
Run Code Online (Sandbox Code Playgroud)
你得到的,在第二种情况:移动line 2到line 4
goal identifier statement
let statement 2
forall statement
let statement 1
other statements
Run Code Online (Sandbox Code Playgroud)
说明
sed -n ' #silent option ON
2{ #if is line 2
h #Replace the contents of the hold space with the contents of the pattern space
:a #label "a"
n #fetch the next line
4{ #if is line 4
p #print line 4
x #Exchange the contents of the hold and pattern spaces
bb #goto "b"
}
H #appends line from the pattern space to the hold space, with a newline before it.
ba #goto "a"
}
:b #Label "b"
p #print
' file
Run Code Online (Sandbox Code Playgroud)
编辑
如果要使用regex标识行,可以修改第一个命令
sed -n '/goal/{p;n;h;:a;n;/forall/{p;x;bb};H;ba};:b;p' file
Run Code Online (Sandbox Code Playgroud)