콘텐츠로 이동

Input/Output format options

(No text to translate)

플랫폼명령어
Ubuntu/Debianwget https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64 -O /usr/local/bin/yq && chmod +x /usr/local/bin/yq
Ubuntu (PPA)sudo add-apt-repository ppa:rmescandon/yq && sudo apt update && sudo apt install yq
macOS (Homebrew)brew install yq
macOS (MacPorts)sudo port install yq
Windows (Chocolatey)choco install yq
Windows (Scoop)scoop install yq
Snapsnap install yq
Gogo install github.com/mikefarah/yq/v4@latest
Dockerdocker run --rm -v "${PWD}":/workdir mikefarah/yq
Alpine Linuxapk add yq
Arch Linuxyay -S yq
Verify Installationyq --version
명령어설명
yq '.' file.yaml전체 YAML 파일 표시 (예쁘게 출력)
yq '.name' file.yaml특정 필드 값 읽기
yq '.metadata.name' file.yaml점 표기법을 사용하여 중첩된 필드 읽기
yq '.items[0]' file.yaml배열의 첫 번째 요소에 접근하기
yq '.items[*]' file.yaml배열의 모든 요소에 접근하기
yq '.items[]' file.yaml배열 요소를 반복합니다
yq '.items[].name' file.yaml모든 배열 요소에서 특정 필드 추출하기
yq '.items[-1]' file.yaml배열의 마지막 요소에 접근하기
yq '.items[1:3]' file.yaml배열 슬라이스 (요소 1과 2)
`cat file.yaml \yq ‘.spec’`
yq -r '.name' file.yaml원시 문자열 (따옴표 없음)
`yq ‘.items \length’ file.yaml`
yq 'keys' file.yaml최상위 키 모두 나열하기
`yq ’.[] \keys’ file.yaml`
명령어설명
yq '.name = "new-value"' file.yaml필드 업데이트 (stdout에 출력)
yq -i '.name = "new-value"' file.yaml필드를 현재 위치에서 업데이트 (파일 수정)
yq '.spec.replicas = 3' file.yaml중첩된 값 업데이트
yq '.items[0].name = "updated"' file.yaml배열 요소 업데이트
yq '.newField = "value"' file.yaml새 필드 생성
yq '.metadata.labels.env = "prod"' file.yaml중첩 필드 생성
yq 'del(.fieldName)' file.yaml필드 삭제
yq 'del(.metadata.annotations)' file.yaml중첩된 필드 삭제
yq 'del(.items[0])' file.yaml배열 요소 삭제
yq '.items += {"name": "new"}' file.yaml배열에 추가하기
yq '.items = []' file.yaml배열 지우기
yq '.count += 1' file.yaml숫자 값 증가
yq '.total = .price * .quantity' file.yaml산술 연산
명령어설명
`yq ‘.items[] \select(.kind == “Pod”)’ file.yaml`
`yq ‘.items[] \select(.kind == “Pod” and .status == “Running”)’ file.yaml`
`yq ‘.items[] \select(.kind == “Pod” or .kind == “Service”)’ file.yaml`
`yq ‘.items[] \select(.name \
`yq ‘.items[] \select(has(“metadata”))’ file.yaml`
`yq ‘.items[] \select(.replicas > 3)’ file.yaml`
`yq ‘.items[] \select(.tags \
`yq ‘.items[] \select(.name != null)’ file.yaml`
`yq ’.[] \select(tag == “!!str”)’ file.yaml`
명령어설명
`yq ‘.items \= sort_by(.name)’ file.yaml`
`yq ‘.items \= sort_by(.metadata.creationTimestamp)’ file.yaml`
`yq ‘.items \= reverse’ file.yaml`
`yq ‘.tags \unique’ file.yaml`
`yq ‘.items \flatten’ file.yaml`
`yq ‘.items \group_by(.kind)’ file.yaml`
`yq ‘.items \map(.name)’ file.yaml`
`yq ‘.items \map(select(.active))’ file.yaml`
yq '.items = .items + .newItems' file.yaml배열 연결하기
`yq ‘.items \= unique_by(.name)’ file.yaml`
yq '[.items[].name]' file.yaml값을 새 배열로 수집하기
명령어설명
yq ea 'select(fi == 0) * select(fi == 1)' f1.yaml f2.yaml두 파일 깊은 병합 (f2가 f1을 덮어씀)
yq ea '. as $item ireduce ({}; . * $item)' *.yaml여러 파일 병합하기
yq ea 'select(fi == 0) *+ select(fi == 1)' f1.yaml f2.yaml배열 연결로 병합하기
yq ea '[.]' file1.yaml file2.yaml파일을 배열로 결합하기
yq '.config = load("config.yaml")' file.yaml외부 파일 로드 및 병합
yq '.spec.template = load("template.yaml").spec' file.yaml파일에서 특정 경로 로드하기
yq ea 'select(fi == 0) *d select(fi == 1)' f1.yaml f2.yaml삭제를 포함한 깊은 병합
명령어설명
yq '.fullName = .firstName + " " + .lastName' file.yaml문자열 연결
`yq ‘.name \= upcase’ file.yaml`
`yq ‘.name \= downcase’ file.yaml`
`yq ‘.name \= trim’ file.yaml`
`yq ‘.text \= sub(“old”, “new”)’ file.yaml`
`yq ‘.text \= gsub(“old”, “new”)’ file.yaml`
`yq ‘.path \split(”/”)’ file.yaml`
`yq ‘.tags \join(”, ”)’ file.yaml`
`yq ‘.name \length’ file.yaml`
`yq ‘.text \contains(“substring”)’ file.yaml`
명령어설명
yq -o=json '.' file.yamlYAML을 JSON으로 변환
yq -P '.' file.jsonJSON을 YAML로 변환
yq -o=xml '.' file.yamlYAML을 XML로 변환
yq -p=xml '.' file.xmlXML을 YAML로 변환
yq -o=csv '.items[]' file.yamlYAML을 CSV로 변환
yq -o=props '.' file.yamlYAML을 properties 형식으로 변환
yq -o=json -I=4 '.' file.yaml사용자 지정 들여쓰기가 있는 JSON
yq -o=yaml --yaml-output-version=1.1 '.' file.yamlYAML 버전 지정
yq -p=csv -o=json '.' file.csvYAML을 통해 CSV를 JSON으로 변환
# Input/Output format options
-p, --input-format string    Input format (yaml/json/xml/csv/props)
-o, --output-format string   Output format (yaml/json/xml/csv/props)
-P, --prettyPrint           Pretty print (shorthand for -o=yaml)

# Modification options
-i, --inplace               Edit file in place
-I, --indent int            Indentation (default 2)

# Processing options
-e, --exit-status           Exit with status code based on result
-n, --null-input            Don't read input, start with null
-N, --no-colors             Disable colored output
-C, --colors                Force colored output

# Multiple file options
ea, eval-all                Evaluate all files together
```## 고급 사용법 - 형식 변환
```yaml
# Basic path expressions
.field                      # Access field
.nested.field              # Nested access
.[0]                       # Array index
.[]                        # Array iteration
.*                         # All fields

# Operators
=                          # Assignment
|=                         # Update assignment
+=                         # Append/increment
*                          # Multiply/merge
+                          # Add/concatenate
-                          # Subtract
//                         # Alternative operator (default value)

# Functions
select()                   # Filter
map()                      # Transform array
has()                      # Check existence
keys                       # Get keys
length                     # Get length
sort_by()                  # Sort array
group_by()                 # Group array
unique                     # Remove duplicates
```## 구성
```bash
# Use environment variables in expressions
export APP_NAME="my-app"
yq '.name = env(APP_NAME)' file.yaml

# With default value
yq '.name = (env(NAME) // "default")' file.yaml

# String interpolation
yq '.message = "Hello " + env(USER)' file.yaml
```### 명령줄 옵션
```bash
# Single deployment
yq -i '.spec.replicas = 5' deployment.yaml

# Multiple deployments in one file
yq -i '(.spec.replicas | select(. != null)) = 5' deployments.yaml

# Conditionally update specific deployment
yq -i '(select(.metadata.name == "api-server") | .spec.replicas) = 10' deployment.yaml

# Update all deployments in multiple files
yq -i '.spec.replicas = 3' k8s/*.yaml
```### 표현식 구문
```bash
# Merge base config with environment-specific overrides
yq ea 'select(fi == 0) * select(fi == 1)' base-config.yaml prod-config.yaml > final-config.yaml

# Merge multiple environment files
yq ea '. as $item ireduce ({}; . * $item)' base.yaml dev.yaml local.yaml > merged.yaml

# Merge with array concatenation
yq ea 'select(fi == 0) *+ select(fi == 1)' config1.yaml config2.yaml > combined.yaml
```### 환경 변수
```bash
# Extract all container images from Kubernetes manifests
yq '.spec.template.spec.containers[].image' deployment.yaml

# Get all service names and ports
yq '.items[] | select(.kind == "Service") | .metadata.name + ":" + (.spec.ports[0].port | tostring)' services.yaml

# Create summary report
yq '.items[] | {"name": .metadata.name, "kind": .kind, "namespace": .metadata.namespace}' resources.yaml -o=json
```## 일반적인 사용 사례
```bash
# Add label to all resources
find . -name "*.yaml" -exec yq -i '.metadata.labels.environment = "production"' {} \;

# Update image tag in all deployments
yq -i '(.spec.template.spec.containers[].image | select(. == "*:latest")) |= sub(":latest", ":v1.2.3")' k8s/**/*.yaml

# Add annotation to specific resources
yq -i 'select(.kind == "Service") | .metadata.annotations."prometheus.io/scrape" = "true"' *.yaml
```### 사용 사례 1: Kubernetes 배포 복제본 업데이트
```bash
# Update version in multiple config files
export VERSION="2.1.0"
yq -i '.version = env(VERSION)' chart/Chart.yaml
yq -i '.image.tag = env(VERSION)' values.yaml

# Inject secrets from environment
yq -i '.database.password = env(DB_PASSWORD)' config.yaml

# Generate environment-specific configs
for env in dev staging prod; do
  yq ea 'select(fi == 0) * select(fi == 1)' base.yaml "env-${env}.yaml" > "config-${env}.yaml"
done
```### 사용 사례 2: 구성 파일 병합
`-i`### 사용 사례 3: 데이터 추출 및 변환
```bash
  yq '.spec.replicas = 5' deployment.yaml  # Preview first
  yq -i '.spec.replicas = 5' deployment.yaml  # Then apply
  ```### 사용 사례 4: 여러 파일에 걸친 대량 업데이트
```bash
  yq '.items[] | select(.name == "test")' file.yaml  # Correct
  ```- **YAML 수정 후 검증하기**: 변경 사항이 유효한 YAML을 생성하는지 확인하세요
```bash
  yq '.' modified.yaml > /dev/null && echo "Valid YAML" || echo "Invalid YAML"
  ```- **사용하기 위해**
`select()`- **조건부 업데이트에 사용하기**: 모든 것을 업데이트하는 것보다 더 정확함
```bash
  yq '(select(.kind == "Deployment") | .spec.replicas) = 3' file.yaml
  ```- **주석 보존하기**: yq는 기본적으로 주석을 보존하지만, 복잡한 변환에는 주의가 필요함
`eval-all`- **다중 파일 작업에 사용하기**: 파일을 개별적으로 처리하는 것보다 더 효율적임
```bash
  yq ea '. as $item ireduce ({}; . * $item)' *.yaml
  ```- **환경 변수 활용하기**: 민감한 데이터를 스크립트에서 제외하세요
```bash
  export SECRET_KEY="..."
  yq '.apiKey = env(SECRET_KEY)' config.yaml
  ```- **스크립팅을 위해 원시 출력 사용하기**: 다른 명령어로 파이핑할 때**
`-r`- **플래그 사용하기**
```bash
  IMAGE=$(yq -r '.spec.template.spec.containers[0].image' deployment.yaml)
  ```- **검증을 위해 종료 코드 확인하기**: null/false 결과에서 실패하도록**
`-e`- **플래그 사용하기**
```bash
  yq -e '.spec.replicas > 0' deployment.yaml && echo "Valid" || echo "Invalid"

문제 해결

문제솔루션
Error: “bad file descriptor”Use -i flag correctly or redirect output: yq '.' file.yaml > temp && mv temp file.yaml
Changes not persistedAdd -i flag for in-place editing: yq -i '.field = "value"' file.yaml
”null” appears in outputField doesn’t exist or is null. Use alternative operator: yq '.field // "default"' file.yaml
Comments are removedUse ... comments="" to explicitly remove, or check if using operations that don’t preserve comments
Array merge replaces instead of concatenatesUse *+ instead of * for merge: yq ea 'select(fi==0) *+ select(fi==1)' f1.yaml f2.yaml
”Error: bad expression”표현식 구문을 확인하고, 적절한 인용을 보장하며, 연산자가 올바른지 검증하세요
Output has extra quotesUse -r flag for raw output: yq -r '.name' file.yaml
Cannot process multiple filesUse ea (eval-all) command: yq ea '.' file1.yaml file2.yaml
Wrong version of yqVerify you have mikefarah/yq (not kislyuk/yq): yq --version should show github.com/mikefarah/yq
Permission denied on -iEnsure write permissions: chmod u+w file.yaml or run with appropriate privileges
Encoding issues with special charactersEnsure UTF-8 encoding: yq --encoding=utf-8 '.' file.yaml
Large files cause memory issuesProcess in chunks or use streaming: yq -N '.items[]' large-file.yaml
Path not found errorsVerify path exists: yq 'has("path.to.field")' file.yaml before accessing
Merge conflicts with complex structuresUse explicit merge strategies: *d for deep merge with deletion, *+ for array concatenation

빠른 참조 - 일반적인 패턴

Would you like me to clarify or complete any specific parts of the translation?```bash

Read value

yq ‘.path.to.field’ file.yaml

Update value

yq -i ‘.path.to.field = “new-value”’ file.yaml

Delete field

yq -i ‘del(.path.to.field)’ file.yaml

Filter array

yq ‘.items[] | select(.name == “target”)’ file.yaml

Merge files

yq ea ‘select(fi==0) * select(fi==1)’ base.yaml override.yaml

Convert format

yq -o=json ’.’ file.yaml

Use environment variable

yq ‘.field = env(VAR_NAME)’ file.yaml

Multiple operations

yq -i ‘.field1 = “value1” | .field2 = “value2”’ file.yaml