首页 > 解决方案 > 如何使用 SED/AWK 将文本文件中的第一行与最后一行交换

问题描述

我正在尝试将unix文件中文本文件中的第一行与最后一行交换:

line1
line2
line3
line4
line5
line6

我想要这样:

line6 
line2
line3
line4
line5
line1

我正在使用sed -n -e '1 s/^.*$/$p' file. 这没有发生。

标签: unixawksed

解决方案


EDIT2:根据 Ed sir 的评论,在这里也添加了这个解决方案,如果第二行是空的,那么它也可以工作。

awk 'NR==1{first=$0;next} NR>2{val=val prev ORS} {prev=$0} END{print prev ORS val first}  Input_file

编辑:仅交换以下第一行和最后一行可能会对您有所帮助(考虑到您的 Input_file 与所示示例相同)。

awk 'FNR==1{first=$0;next} {val=(val?val ORS prev:prev?$0:"")} {prev=$0} END{print $0 ORS val ORS first}' Input_file

解释:

awk '
FNR==1{                            ##Checking if line is first line then do following.
  first=$0;                        ##Creating varable first whose value is current line value.
  next                             ##next will skip all further statements from here.
}
{
  val=(val?val ORS prev:prev?$0:"")  ##Creating variable named val here whoe value is concatenating to its own value with variable prev value.
}
{
  prev=$0                          ##Creating variable prev whose value will be current value of line but will become previous value for next line.
}
END{
  print $0 ORS val ORS first       ##Printing current line ORS val ORS and first here.
}'  Input_file                     ##Mentioning Input_file name here.

您能否尝试关注并让我知道这是否对您有帮助。

awk -v from=1 -v to=6 'FNR==from{source=$0;next} FNR==to{target=$0;next} {val=val?val ORS $0:$0} END{print target ORS val ORS source}' Input_file

推荐阅读