쉘 스크립트를 사용하여 배열에서 유사한 파일 이름 제외

쉘 스크립트를 사용하여 배열에서 유사한 파일 이름 제외

예를 들어 파일 배열이 있습니다 file=[a.yml, a.json,b.yml,b.json]. 루프를 사용하여 반복하고 있습니다 for. 배열에 또는 및 가 .json모두 있는 경우 파일이 실행되지 않도록 제외해야 합니다 . 하지만 배열에만 있는 경우 (예 : 루프를 통과해야 합니다. 쉘 스크립트로 가능합니까?).yml.yaml.json.json[a.json,b.json]

기본적으로 배열의 문자열을 비교하고 중복 항목을 동적으로 제외하려고 합니다.

쉘로 가능합니까?


filename=$(git show --pretty="format:" --name-only $CODEBUILD_RESOLVED_SOURCE_VERSION)
echo "$filename"
mkdir report || echo "dir report exists"
for file in ${filename}; do
    echo ${file}
    ext=${file##*.}
    if [ $ext == "yaml" ] || [ $ext == "yml" ] || [ $ext == "json" ]; then
        if [ ${file} != "buildspec.yml" ] && [ ${file} != "stackupdatebuildspec.yml" ] && [ ${file} != "specs.json" ]; then
            stack=$(echo ${file} | cut -d "." -f 1)
            stackName="${stack//[\/]/-}"
            echo ${stackName}
            howmany() { echo $#; }
            numOfFilesValidated=$(howmany $listOfFilesToScan)
            echo "=========================================== Syntax validation started =============================================================="
            cfSyntaxLogFile="cf-syntax-validation-output"
            numOfFailures=0
            numOfValidatedFiles=0
            for file_to_scan in $listOfFilesToScan; do
                if [[ $(cfn-lint -t "$file_to_scan" --parameter-values-path "${stack}.json" --append-rules ./append_rules --override-spec ./over_ride_spec/spec.json |& tee -a $cfSyntaxLogFile) == "" ]]; then
                    echo "INFO: Syntax validation of template $file: SUCCESS"
                    ((numOfValidatedFiles++))
                else
                    echo "ERROR: Syntax validation of template $file: FAILURE"
                    ((numOfFailures++))
                fi
            done'''

답변1

계속 진행하기 전에 다른 값이 있는지 확인할 수 있습니다.Bash 배열에 값이 포함되어 있는지 확인.

배열에 파일 만 보관 .json하고 나중에 루프에서 파일이 있는지 확인할 수도 있습니다 .yml.

bash이에 대한 좋은 매개변수 대체가 있습니다.

${parameter%word}

Remove matching suffix pattern.

귀하의 경우에는 다음과 같습니다(을 제거 .json하고 다음을 추가함 .yml).

if [ ! -f "${filename%.json}.yml" ]
then
    # process
fi

답변2

다음과 같이 시도해 보십시오.

declare -A fhash

# Load $files array with 'git show -z' - NUL-separated filenames in case
# of spaces, newlines, etc.
mapfile -d '' -t files < <(git show -z --pretty="format:" --name-only "$CODEBUILD_RESOLVED_SOURCE_VERSION")

# build an associative array (hash) from the files array, so we can easily
# check if a matching .yml filename exists for .json and .yaml files.
for f in "${files[@]}"; do
  fhash["$f"]=1
done

# now process each of the filenames in the $files array.
for f in "${files[@]}"; do
  # ignore these filenames
  [[ $f =~ ^(buildspec.yml|stackupdatebuildspec.yml|specs.json)$ ]] && continue

  base=${f%.*}       # get base filename
  ext=".${f##*.}"    # get file's "extension"

  # ignore '.json' and .'yaml' files if there is a matching .yml filename.
  # also ignore .json files if there is a matching .yaml filename
  [[ $ext =~ \.(json|yaml)$ ]] && [ "${fhash[$base.yml]}"  -eq 1 ] && continue
  [[ $ext =~ \.json$        ]] && [ "${fhash[$base.yaml]}" -eq 1 ] && continue

  # The code so far has skipped/ignored all of the files we don't want to
  # process, so you can do whatever you need with "$f".

  # ... your code here ...
done

관련 정보