为方便起见,我正在尝试对齐文件内容。所有分散的变量都在一行中。也是一阶中最小的变量名。有人可以帮助我使用sed,awk或VIM编辑器来实现这一目标吗?
实际文件内容
variable "key_name" {
default = ""
}
variable "vpc_id" {
default = ""
}
variable "name" {
default = ""
}
variable "ami" {
default = ""
}
variable "instance_type" {
default = ""
}
variable "name_suffix" {
default = ""
}
variable "additional_volume_size" {
default = ""
}
预期产量
variable "ami" { default = "" }
variable "name" { default = "" }
variable "vpc_id" { default = "" }
variable "key_name" { default = "" }
variable "name_suffix" { default = "" }
variable "instance_type" { default = "" }
variable "additional_volume_size" { default = "" }
答案 0 :(得分:4)
使用awk
和column
:
awk 'BEGIN{RS="";FS="\n";OFS=" "}{$1=$1}1' file | column -t
输出:
variable "key_name" { default = "" }
variable "vpc_id" { default = "" }
variable "name" { default = "" }
variable "ami" { default = "" }
variable "instance_type" { default = "" }
variable "name_suffix" { default = "" }
variable "additional_volume_size" { default = "" }
如果要按变量名的长度对输出进行排序,可以使用awk
输出长度,然后用管道将其排序并删除长度,如下所示:
awk 'BEGIN{RS="";OFS=" "}{$1=length($2)" "$1}1' file \
| sort -k1,1n \
| cut -d' ' -f2- \
| column -t
输出:
variable "ami" { default = "" }
variable "name" { default = "" }
variable "vpc_id" { default = "" }
variable "key_name" { default = "" }
variable "name_suffix" { default = "" }
variable "instance_type" { default = "" }
variable "additional_volume_size" { default = "" }