Program Tip

두 문자열을 연결하여 완전한 경로를 만드는 방법

programtip 2020. 10. 9. 12:19
반응형

두 문자열을 연결하여 완전한 경로를 만드는 방법


bash 스크립트를 작성하려고합니다. 이 스크립트에서 사용자가 디렉토리 경로를 입력하기를 원합니다. 그런 다음이 문자열 끝에 문자열을 추가하고 일부 하위 디렉터리에 대한 경로를 만들고 싶습니다. 예를 들어 사용자가 다음과 같은 문자열을 입력한다고 가정합니다.

/home/user1/MyFolder

이제이 디렉토리에 2 개의 하위 디렉토리를 만들고 거기에 일부 파일을 복사합니다.

/home/user1/MyFolder/subFold1
/home/user1/MyFolder/subFold2

어떻게 할 수 있습니까?


POSIX 표준은 여러 개 //파일 이름에서 단일 취급 하도록 요구합니다 . 이와 //dir///subdir////file동일하다 /dir/subdir/file.

전체 경로를 구축하기 위해 두 문자열을 연결하는 것은 다음과 같이 간단합니다.

full_path="$part1/$part2"

#!/bin/bash

read -p "Enter a directory: " BASEPATH

SUBFOLD1=${BASEPATH%%/}/subFold1
SUBFOLD2=${BASEPATH%%/}/subFold2

echo "I will create $SUBFOLD1 and $SUBFOLD2"

# mkdir -p $SUBFOLD1
# mkdir -p $SUBFOLD2

그리고 readline을 사용하여 완료와 모든 것을 얻으려면 -e다음 호출에 a 추가하십시오 read.

read -e -p "Enter a directory: " BASEPATH

단순히 경로의 일부를 연결하여 원하는 것을 달성하지 않습니까?

$ base="/home/user1/MyFolder"
$ subdir="subFold1"
$ new_path=$base$subdir
$ echo $new_path
/home/user1/MyFoldersubFold1

그런 다음 필요에 따라 폴더 / 디렉토리를 만들 수 있습니다.


다음 스크립트는 상대 경로 (SUBDIR)로 여러 (상대 / 절대) 경로 (BASEPATH)를 연결합니다.

shopt -s extglob
SUBDIR="subdir"
for BASEPATH in '' / base base/ base// /base /base/ /base//; do
  echo "BASEPATH = \"$BASEPATH\" --> ${BASEPATH%%+(/)}${BASEPATH:+/}$SUBDIR"
done

그 결과는 다음과 같습니다.

BASEPATH = "" --> subdir
BASEPATH = "/" --> /subdir
BASEPATH = "base" --> base/subdir
BASEPATH = "base/" --> base/subdir
BASEPATH = "base//" --> base/subdir
BASEPATH = "/base" --> /base/subdir
BASEPATH = "/base/" --> /base/subdir
BASEPATH = "/base//" --> /base/subdir

shopt -s extglobBASEPATH은 (넌센스 아마 인) 여러 슬래시에 종료 할 수 있도록에만 필요합니다. 확장 된 글 로빙없이 다음을 사용할 수 있습니다.

echo ${BASEPATH%%/}${BASEPATH:+/}$SUBDIR

덜 깔끔하지만 여전히 작동합니다.

BASEPATH = "" --> subdir
BASEPATH = "/" --> /subdir
BASEPATH = "base" --> base/subdir
BASEPATH = "base/" --> base/subdir
BASEPATH = "base//" --> base//subdir
BASEPATH = "/base" --> /base/subdir
BASEPATH = "/base/" --> /base/subdir
BASEPATH = "/base//" --> /base//subdir

#!/usr/bin/env bash

mvFiles() {
    local -a files=( file1 file2 ... ) \
             subDirs=( subDir1 subDir2 ) \
             subDirs=( "${subDirs[@]/#/$baseDir/}" )

    mkdir -p "${subDirs[@]}" || return 1

    local x
    for x in "${subDirs[@]}"; do
        cp "${files[@]}" "$x"
    done
}



main() {
    local baseDir
    [[ -t 1 ]] && echo 'Enter a path:'
    read -re baseDir
    mvFiles "$baseDir"
}

main "$@"

이것은 빈 dir에서 작동합니다 (두 번째 문자열이 /절대 경로로 취급되어야하는 것으로 시작하는지 확인해야 할 수도 있습니다 .) :

#!/bin/bash

join_path() {
    echo "${1:+$1/}$2" | sed 's#//#/#g'
}

join_path "" a.bin
join_path "/data" a.bin
join_path "/data/" a.bin

산출:

a.bin
/data/a.bin
/data/a.bin

참조 : 쉘 매개 변수 확장


나는 당신과 같은 경로 결합 작업을 수행 해야하는 쉘 스크립트로 작업하고있었습니다.

문제는 두 경로 모두

/data/foo/bar

/data/foo/bar/ 

유효합니다.

이 경로에 파일을 추가하려면

/data/foo/bar/myfile

there was no native method (like os.path.join() in python) in shell to handle such situation.

But I did found a trick

For example , the base path was store in a shell variable

BASE=~/mydir

and the last file name you wanna join was

FILE=myfile

Then you can assign your new path like this

NEW_PATH=$(realpath ${BASE})/FILE

and then you`ll get

$ echo $NEW_PATH

/path/to/your/home/mydir/myfile

the reason is quiet simple, the "realpath" command would always trim the terminating slash for you if necessary

참고URL : https://stackoverflow.com/questions/11226322/how-to-concatenate-two-strings-to-build-a-complete-path

반응형