Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 如何在shell中向下移动一条线?_Bash_Shell_Unix_Sed - Fatal编程技术网

Bash 如何在shell中向下移动一条线?

Bash 如何在shell中向下移动一条线?,bash,shell,unix,sed,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 您可以使用awk: awk -v n=3 'NR==n{line=$0; next} NR==n+2{pr

如何根据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

您可以使用
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
如果不使用gnu awk,则

awk -v n=3 'NR==n{line=$0; next} NR==n+2{print line} 1' file > _file.tmp &&
mv _file.tmp file
使用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将第3行保存在保留空间(
h
)中,不打印就跳到下一行(
d

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

要就地覆盖文件,请执行以下操作:

sed -i.bak '3{h;d}; 4{p;x}' file
可供替代的 使用GNU sed(OSX上的gsed):


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

非常感谢!您在哪里指定行
3
?我需要能够对任何行号执行此操作,不包括最后一行。您可以在命令行选项中传递任何行号,例如,对于行#5如何覆盖
ex.file
?使用gnu awk可以执行:
awk-I inplace-v n=3'NR==n{line=$0;next}NR==n+2{print line}1'文件
也许我们应该将此评论移至答案的正文谢谢。如何将覆盖
ex.file
合并到这些命令中?@kilojoules With
sed
,要覆盖文件,请使用
-I.bak
选项。(这将创建一个扩展名为
.bak
的备份文件。如果您不想这样做,则需要告诉我您使用的是哪个操作系统。)
$ 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