如何使用SED/AWK将文本文件中的第一行与最后一行交换 [英] How to swap the first line with last line in a text file using SED/AWK

查看:421
本文介绍了如何使用SED/AWK将文本文件中的第一行与最后一行交换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to swap the first line with last line in a text file in unix file has:

line1
line2
line3
line4
line5
line6

我想要这样:

line6 
line2
line3
line4
line5
line1

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

I am using sed -n -e '1 s/^.*$/$p' file . Which is not happening.

推荐答案

第二行为空,那么它也将起作用.

As per Ed sir's comment adding this solution too here which will be more suitable in case 2nd line is empty then also it will work.

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


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


To exchange only first and last line following may help you(considering that your Input_file is same as shown sample).

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

说明:

Explanation:

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.

能否请您尝试以下操作,如果有帮助,请告诉我.

Could you please try following and let me know if this helps you.

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

这篇关于如何使用SED/AWK将文本文件中的第一行与最后一行交换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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