使用sed更改文件中一行的位置 [英] change the position of a line in a file using sed

查看:41
本文介绍了使用sed更改文件中一行的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何更改文件中一行的位置(最好使用sed).例如,考虑包含

I would like to know how to change the position of a line in a file (preferably using sed). For example, consider the file that contains

goal identifier statement  
let statement 1  
let statement 2  
forall statement  
other statements

我希望能够做到这一点

goal identifier statement  
forall statement  
let statement 1  
let statement 2  
other statements  

我在其中更改 all 行的位置,并将其放在 goal 行之后. forall goal 是可用于识别行的正则表达式.

where I change the position of the forall line and bring it after the goal line. forall and goal are regexps that can be used to identify the lines.

推荐答案

您可以尝试将第4行移动到第2行,我要移动A行 B 行,其中 A> B

you can try, for move line 4 to line 2, I want to move line A to line B, where A>B

sed -n '2{h; :a; n; 4{p;x;bb}; H; ba}; :b; p' file

A< B

sed -n '2{h; d}; 4{p; x;}; p' file

在第一种情况下,您得到:将第4行移至第2行

you get, in first case: move line 4 to line 2

goal identifier statement
forall statement
let statement 1
let statement 2
other statements

在第二种情况下,您得到:将第2行移至第4行

you get, in second case: move line 2 to line 4

goal identifier statement  
let statement 2  
forall statement  
let statement 1  
other statements

说明

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 

编辑

如果要使用 regex 标识行,则可以修改第一个命令

If You want use regex for identify the lines, you can modify first command

sed -n '/goal/{p;n;h;:a;n;/forall/{p;x;bb};H;ba};:b;p' file

这篇关于使用sed更改文件中一行的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆