如何在壳中移动线?

时间:2016-08-10 05:02:50

标签: bash shell unix sed

如何根据行号在shell中向下移动一行?

对于示例文件ex.file,

stuff
other stuff
I want this line to go down one
more stuff
more stuff

我希望更改此文件,使其显示为:

stuff
other stuff
more stuff
I want this line to go down one
more stuff

2 个答案:

答案 0 :(得分:4)

您可以使用<field name="face_book_icon" type="radio" default="" label="Face Book Icon" description="Face Book Icon" > <option value="facebook-official" class="fa fa-facebook-official " > icon 1</option> <option value="facebook" class="fa fa-facebook"> icon 2</option> <option value="facebook-square" class="fa fa-facebook-square" >icon 3</option> </field>

awk

使用gnu awk将更改保存回文件:

awk -v n=3 'NR==n{line=$0; next} NR==n+2{print line} 1' file

stuff
other stuff
more stuff
I want this line to go down one
more stuff

如果不使用gnu awk那么

awk -i inplace -v n=3 'NR==n{line=$0; next} NR==n+2{print line} 1' file

答案 1 :(得分:2)

使用sed:

$ sed '3{h;d}; 4{p;x}' file
stuff
other stuff
more stuff
I want this line to go down one
more stuff

3{h;d}告诉sed在保留空间(h)中保存第3行并跳转到下一行而不打印(d)。

4{p;x}告诉sed打印第4行(p),然后检索保留空间中的行(第3行),以便打印它(x)。

要覆盖文件:

sed -i.bak '3{h;d}; 4{p;x}' file

替代

使用GNU sed(在OSX上引用):

$ sed -E '3 {N; s/(.*)\n(.*)/\2\n\1/}' file
stuff
other stuff
more stuff
I want this line to go down one
more stuff

在第3行,这告诉sed将下一行(第4行)附加到模式空间,然后执行替换命令以交换两行的顺序。