unix - 如何使用 SED/AWK 将文本文件中的第一行与最后一行交换
问题描述
我正在尝试将unix文件中文本文件中的第一行与最后一行交换:
line1
line2
line3
line4
line5
line6
我想要这样:
line6
line2
line3
line4
line5
line1
我正在使用sed -n -e '1 s/^.*$/$p' file
. 这没有发生。
解决方案
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
推荐阅读
- javascript - 将 Google DFP 广告单元标题(“广告”)添加到所有具有白色背景和内边距的广告
- angular - 角度材料侧边栏显示水平
- git - 按下“变基并合并”后,已验证的签名消失了
- powerbi - 有没有办法将书签按钮的数量转换为 PowerBI 中的下拉列表/切片器?
- node.js - 在一个 Firebase 云函数中使用 100 多个路由并将路由拆分到多个云函数时,性能有何不同?
- php - Laravel ui 安装后登录错误
- jquery - Jquery if/else 与下面的代码冲突
- laravel - Vue 有时在我的 Laravel + Bootstrap 4 应用程序中加载太晚(?)
- graphql - GraphQL / Strapi - 无法按字符串字段过滤
- clickhouse - ClickHouse 上由 '_nd' 完成的表格的目的是什么