![같은 문구로 시작하는 여러 줄을 하나로 결합](https://linux55.com/image/217190/%EA%B0%99%EC%9D%80%20%EB%AC%B8%EA%B5%AC%EB%A1%9C%20%EC%8B%9C%EC%9E%91%ED%95%98%EB%8A%94%20%EC%97%AC%EB%9F%AC%20%EC%A4%84%EC%9D%84%20%ED%95%98%EB%82%98%EB%A1%9C%20%EA%B2%B0%ED%95%A9.png)
Arch Linux 패키지를 제가 작성하고 있는 패키지 관리자의 형식으로 변환하기 위해 Bash 스크립트를 작성 중인데 일부 메타데이터 파일을 파일 형식으로 변환해야 합니다 .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
입력 파일에서 "...other stuff.." 부분을 제외하려면 다음 코드를 사용할 수 있습니다.
$ awk -F"=" 'NR==1{printf $1 " = [" } {printf $2 ","};END{print""}' infile | sed 's/.$/\]/'
depends = [ "some-dependency", "another-dependency", "yet-another-dependency"]