我正在编写一个 Bash 脚本,将 Arch Linux 包转换为我正在编写的包管理器的格式,并且我必须将一些元数据文件转换为文件格式.toml
。以前,我一直在使用sed
,但我只需要一些可以在 Bash 脚本中实现的东西。转换应如下所示。
输入:
... other stuff ...
depends = "some-dependency"
depends = "another-dependency"
depends = "yet-another-dependency"
输出:
... other stuff already converted ...
depends = [ "some-dependency", "another-dependency", "yet-another-dependency" ]
答案1
使用awk
:
awk -F' = ' '
$1 == "depends" {
printf "%s %s", (flag!=1 ? "depends = [" : ","), $2
flag=1
next
}
flag {
print " ]"
flag=0
}
{ print }
END {
if (flag) print " ]"
}
' file
输入:
... other stuff ...
depends = "some-dependency"
depends = "another-dependency"
depends = "yet-another-dependency"
... more stuff ...
depends = "next-dependency"
depends = "and-another-dependency"
输出:
... other stuff ...
depends = [ "some-dependency", "another-dependency", "yet-another-dependency" ]
... more stuff ...
depends = [ "next-dependency", "and-another-dependency" ]
答案2
从输入文件中排除“...其他东西..”部分,您可以使用以下代码:
$ awk -F"=" 'NR==1{printf $1 " = [" } {printf $2 ","};END{print""}' infile | sed 's/.$/\]/'
depends = [ "some-dependency", "another-dependency", "yet-another-dependency"]