簡體   English   中英

嘗試替換行時,如果“sed:無輸入文件”出現 sed 錯誤

[英]Sed error in if "sed: no input files" when try replace lines

我嘗試更改 yaml 文件中的副本數。 我的腳本發現需要我的信息並且必須從鍵盤讀取文本但他跳過閱讀並向我發送“sed:無輸入文件”。 我做錯了什么? 感謝您的關注

#!/bin/bash
FILES=./test1/*

for file in $FILES
do
    echo "$file"
    grep -v -e "commonconfigs" -e "commonsecrets" -e "internalurls" $file | grep -w "[^-] name:\|replicas:"
    while IFS= read line
    do
    currentline=$(echo "$line" | grep -o "replicas")
      if  [ "$currentline" == "replicas" ];then
        read -p "replics:" rep
        sed -i 's/replicas:.*/replicas:$rep/g' > "$line"
      fi
    done < "$file"
done

輸出:

./test1/anal.yaml
  name: anal
  replicas: 1
  name: anal
template:
sed: no input files

示例文件

apiVersion: apps/v1
kind: Deployment
metadata:
  name: devices-api
spec:
  selector:
  replicas: 1
  template:
    metadata:
        fluentd: "true"
      annotations:
        prometheus.io/scrape: 'true'
    spec:
      containers:
      - name: devices-api
        image:
        imagePullPolicy: "Always"
        resources: {}
        env:
          - name: Swagger__Enabled
            valueFrom:
              configMapKeyRef:
                name: commonconfigs
---

apiVersion: apps/v1
kind: Deployment
metadata:
  selector:
      app: event-jobs
  replicas: 1
  template:

你的代碼的下一個語句是有罪的:

do [...] sed -i 's/replicas:.*/replicas:$rep/g' > "$line" [...] done < "$file"

使用選項-i調用的sed命令用於就地編輯文件,如果您從標准輸入(在 do-while 循環之外)讀取文件,則這是不可能的。

如果您的目標是替換replicas:在 yaml 文件中,則無需使用whilegrep 使用這個sed命令:

sed "s/\<replicas:.*/replicas: $rep/g" test1/*yaml

雙引號而不是單引號允許$rep參數擴展。 首先測試它,如果輸出看起來不錯,請使用 sed -i''選項替換文件。

謝謝大家的回答。 我的問題將出在我的算法解析上。 我嘗試閱讀每一行並將它們設置在 sed 中。

sed -i "$32 s|replicas:.*|replicas: $rep|" $file

現在我找到了 grep 的行數並將它們設置在數組中並設置在 sed 中我需要更改某些內容的位置

解析我的文件的解決方案:

#!/bin/bash
FILES=*yaml

for file in $FILES
do
    echo $file
    grep -v -e "commonconfigs" $file | grep -w "[^-] name:\|replicas:"
    nummeric=($(grep -n "replicas" $file | cut -f1 -d:))
    for i in "${nummeric[@]}"; do
      echo $i
      read -p "replicas: " rep
      sed -i "$i s|replicas:.*|replicas: $rep|" $file
    done
done

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM