Programing

파일의 전체 경로를 얻는 방법은 무엇입니까?

crosscheck 2020. 10. 2. 21:33
반응형

파일의 전체 경로를 얻는 방법은 무엇입니까?


의 전체 경로를 쉽게 인쇄 할 수있는 방법이 file.txt있습니까?

file.txt = /nfs/an/disks/jj/home/dir/file.txt

그만큼 <command>

dir> <command> file.txt  

인쇄해야

/nfs/an/disks/jj/home/dir/file.txt

readlink 사용 :

readlink -f file.txt

Linux를 사용하고 있다고 가정합니다.

realpathcoreutils 8.15 라는 유틸리티를 찾았습니다 .

realpath file.txt
/data/ail_data/transformed_binaries/coreutils/test_folder_realpath/file.txt

@ styrofoam-fly 및 @ arch-standton 주석 realpath에 따라 파일 존재 여부를 확인하지 않고이 문제를 해결하기 위해 e인수를 추가합니다 .realpath -e file


다음은 일반적으로 트릭을 수행합니다.

 echo $(cd $(dirname "$1") && pwd -P)/$(basename "$1")

더 쉬운 방법이 있다는 것을 알고 있지만 찾을 수 있다면 감히 ...

jcomeau@intrepid:~$ python -c 'import os; print(os.path.abspath("cat.wav"))'
/home/jcomeau/cat.wav

jcomeau@intrepid:~$ ls $PWD/cat.wav
/home/jcomeau/cat.wav

find $PWD -type f | grep "filename"

또는

find $PWD -type f -name "*filename*"

파일과 동일한 디렉토리에있는 경우 :

ls "`pwd`/file.txt"

file.txt대상 파일 이름으로 바꿉니다 .


Windows에서는 다음을 수행 할 수 있습니다.

  • Shift 키를 누른 상태에서 파일을 마우스 오른쪽 버튼으로 클릭하면 "Copy as Path"

    그러면 파일의 전체 경로가 클립 보드에 복사됩니다.

Linux에서는 다음 명령을 사용할 수 있습니다.

  • realpath yourfile 많은 사람들이 제안한 파일의 전체 경로를 가져옵니다.

나는 이것이 지금 오래된 질문이라는 것을 알고 있지만 여기에 정보를 추가하기 위해 :

Linux 명령 which을 사용하여 명령 파일의 파일 경로를 찾을 수 있습니다.

$ which ls
/bin/ls

이에 대한 몇 가지주의 사항이 있습니다. https://www.cyberciti.biz/faq/how-do-i-find-the-path-to-a-command-file/을 참조 하십시오 .


fpn (전체 경로 이름) 스크립트를 사용할 수 있습니다 .

% pwd
/Users/adamatan/bins/scripts/fpn

% ls
LICENSE   README.md fpn.py

% fpn *
/Users/adamatan/bins/scripts/fpn/LICENSE
/Users/adamatan/bins/scripts/fpn/README.md
/Users/adamatan/bins/scripts/fpn/fpn.py

fpn은 표준 Linux 패키지는 아니지만 무료 개방형 github 프로젝트 이며 1 분 안에 설정할 수 있습니다.


Mac, Linux, * nix에서 작동합니다.

이것은 현재 디렉토리에있는 모든 파일의 인용 된 csv를 제공합니다 :

ls | xargs -I {} echo "$(pwd -P)/{}" | xargs | sed 's/ /","/g'

이것의 출력은 파이썬 목록이나 유사한 데이터 구조에 쉽게 복사 할 수 있습니다.


비슷한 시나리오에서 다른 위치에서 cshell 스크립트를 시작합니다. 지정된 디렉터리에서만 실행되도록 스크립트의 올바른 절대 경로를 설정하기 위해 다음 코드를 사용하고 있습니다.

set script_dir = `pwd`/`dirname $0`

$0 스크립트가 어떻게 실행되었는지 정확한 문자열을 저장합니다.

스크립트는 다음과 같이 시작되었다 경우 예를 들면 : $> ../../test/test.csh, $script_dir포함/home/abc/sandbox/v1/../../test


Mac OS X의 경우 운영 체제와 함께 제공되는 유틸리티를 교체하고 최신 버전의 coreutils로 교체했습니다. 이를 통해 Mac에서 ( readlink -f파일에 대한 절대 경로) 및 realpath(디렉토리에 대한 절대 경로)와 같은 도구에 액세스 할 수 있습니다 .

Homebrew 버전은 명령 이름 앞에 'G'(GNU 도구의 경우)를 추가하므로 등가물은 greadlink -f FILEgrealpath DIRECTORY.

Homebrew를 통해 Mac OS X에 coreutils / GNU 도구를 설치하는 방법에 대한 지침은 이 StackExchange 문서 에서 찾을 수 있습니다 .

주의 : readlink -frealpath명령은 Mac Unix 사용자가 아닌 경우 즉시 사용할 수 있습니다.


echo $(cd $(dirname "$1") && pwd -P)/$(basename "$1")

이것은 @ZeRemz의 답변 에서 일어나는 일에 대한 설명입니다 .

  1. 이 스크립트는 상대 경로를 인수로 가져옵니다. "$1"
  2. 그런 다음 해당 경로의 dirname 부분을 얻습니다 (이 스크립트에 dir 또는 파일을 전달할 수 있음).dirname "$1"
  3. 그런 다음 우리 cd "$(dirname "$1")는이 상대 디렉토리에
  4. && pwd -P그리고 그것에 대한 절대 경로를 얻으십시오. -P옵션은 모든 심볼릭 링크를 피합니다
  5. 그 후 절대 경로에 basename추가 합니다.$(basename "$1")
  6. 마지막 단계는 우리로 echo그것을

이 기능을 사용할 수 있습니다. 파일 이름이 상대 경로없이 제공되면 현재 작업 디렉토리에있는 것으로 간주됩니다.

abspath() { old=`pwd`;new=$(dirname "$1");if [ "$new" != "." ]; then cd $new; fi;file=`pwd`/$(basename "$1");cd $old;echo $file; }

용법:

$ abspath file.txt
/I/am/in/present/dir/file.txt

상대 경로와 함께 사용 :

$ abspath ../../some/dir/some-file.txt
/I/am/in/some/dir/some-file.txt

파일 이름에 공백 포함 :

$ abspath "../../some/dir/another file.txt"
/I/am/in/some/dir/another file.txt

이것은 나를 위해 꽤 잘 작동했습니다. 파일 시스템 (필요에 따라 찬반 양론)에 의존하지 않으므로 빠릅니다. 그리고 대부분의 * NIX에 이식 가능해야합니다. 전달 된 문자열이 실제로 다른 디렉토리가 아닌 PWD에 상대적이라고 가정합니다.

function abspath () {
   echo $1 | awk '\
      # Root parent directory refs to the PWD for replacement below
      /^\.\.\// { sub("^", "./") } \
      # Replace the symbolic PWD refs with the absolute PWD \
      /^\.\//   { sub("^\.", ENVIRON["PWD"])} \
      # Print absolute paths \
      /^\//   {print} \'
}

이것은 순진하지만 POSIX를 준수하도록 만들어야했습니다. 파일의 디렉토리로 cd 할 수있는 권한이 필요합니다.

#!/bin/sh
if [ ${#} = 0 ]; then
  echo "Error: 0 args. need 1" >&2
  exit 1
fi


if [ -d ${1} ]; then


  # Directory


  base=$( cd ${1}; echo ${PWD##*/} )
  dir=$( cd ${1}; echo ${PWD%${base}} )

  if [ ${dir} = / ]; then
    parentPath=${dir}
  else
    parentPath=${dir%/}
  fi

  if [ -z ${base} ] || [ -z ${parentPath} ]; then
    if [ -n ${1} ]; then
      fullPath=$( cd ${1}; echo ${PWD} )
    else
      echo "Error: unsupported scenario 1" >&2
      exit 1
    fi
  fi

elif [ ${1%/*} = ${1} ]; then

  if [ -f ./${1} ]; then


    # File in current directory

    base=$( echo ${1##*/} )
    parentPath=$( echo ${PWD} )

  else
    echo "Error: unsupported scenario 2" >&2
    exit 1
  fi
elif [ -f ${1} ] && [ -d ${1%/*} ]; then


  # File in directory

  base=$( echo ${1##*/} )
  parentPath=$( cd ${1%/*}; echo ${PWD} )

else
  echo "Error: not file or directory" >&2
  exit 1
fi

if [ ${parentPath} = / ]; then
  fullPath=${fullPath:-${parentPath}${base}}
fi

fullPath=${fullPath:-${parentPath}/${base}}

if [ ! -e ${fullPath} ]; then
  echo "Error: does not exist" >&2
  exit 1
fi

echo ${fullPath}

이것을 "shell.rc"에 저장하거나 콘솔에 넣을 수 있습니다.

function absolute_path {echo "$ PWD / $ 1"; }

alias ap = "absolute_path"

예:

ap somefile.txt

출력됩니다

/home/user/somefile.txt


find / -samefile file.txt -print

Will find all the links to the file with the same inode number as file.txt

adding a -xdev flag will avoid find to cross device boundaries ("mount points"). (But this will probably cause nothing to be found if the find does not start at a directory on the same device as file.txt)

Do note that find can report multiple paths for a single filesystem object, because an Inode can be linked by more than one directory entry, possibly even using different names. For instance:

find /bin -samefile /bin/gunzip -ls

Will output:

12845178    4 -rwxr-xr-x   2 root     root         2251 feb  9  2012 /bin/uncompress
12845178    4 -rwxr-xr-x   2 root     root         2251 feb  9  2012 /bin/gunzip

This will work for both file and folder:

getAbsolutePath(){
    [[ -d $1 ]] && { cd "$1"; echo "$(pwd -P)"; } || 
    { cd "$(dirname "$1")" || exit 1; echo "$(pwd -P)/$(basename "$1")"; }
}

Usually:

find `pwd` | grep <filename>

Alternatively, just for the current folder:

find `pwd` -maxdepth 1 | grep <filename>

I like many of the answers already given, but I have found this really useful, especially within a script to get the full path of a file, including following symlinks and relative references such as . and ..

dirname `readlink -e relative/path/to/file`

Which will return the full path of the file from the root path onwards. This can be used in a script so that the script knows which path it is running from, which is useful in a repository clone which could be located anywhere on a machine.

basePath=`dirname \`readlink -e $0\``

I can then use the ${basePath} variable in my scripts to directly reference other scripts.

Hope this helps,

Dave


This works with both Linux and Mac OSX ..

 echo $(pwd)$/$(ls file.txt)

Another Linux utility, that does this job:

fname <file>

Mac OS의 경우 파인더에서 파일의 경로 만 확인하려면 파일을 제어하고 하단의 "서비스"로 스크롤합니다. "복사 경로"및 "전체 경로 복사"를 포함하여 많은 선택 사항이 있습니다. 이 중 하나를 클릭하면 경로가 클립 보드에 저장됩니다.


fp () {
PHYS_DIR=`pwd -P`
RESULT=$PHYS_DIR/$1
echo $RESULT | pbcopy
echo $RESULT
}

텍스트를 클립 보드에 복사하고 터미널 창에 텍스트를 표시합니다.

:)

(다른 스택 오버플로 답변에서 일부 코드를 복사했지만 더 이상 해당 답변을 찾을 수 없습니다)


내가 찾은 가장 쉬운 방법은

for i in `ls`; do echo "`pwd`/$i"; done

그것은 나를 위해 잘 작동합니다


Mac OSX에서 다음 단계를 수행하십시오.

  1. cd 대상 파일의 디렉토리에.
  2. 다음 터미널 명령 중 하나를 입력하십시오.
단말기
ls "`pwd`/file.txt"
echo $(pwd)/file.txt
  1. file.txt실제 파일 이름으로 바꿉니다 .
  2. 프레스 Enter

아래에 언급 된 Mac에서는 라인이 작동합니다. 멋진 라인을 추가 할 필요가 없습니다.

> pwd filename

"readlink -f"외에 일반적으로 사용되는 또 다른 명령 :

$find  /the/long/path/but/I/can/use/TAB/to/auto/it/to/ -name myfile
/the/long/path/but/I/can/use/TAB/to/auto/it/to/myfile
$

This also give the full path and file name at console

Off-topic: This method just gives relative links, not absolute. The readlink -f command is the right one.


Create a function like the below (echoes the absolute path of a file with pwd and adds the file at the end of the path:

abspath() { echo $(pwd "$1")/"$1"; }

Now you can just find any file path:

abspath myfile.ext

참고URL : https://stackoverflow.com/questions/5265702/how-to-get-full-path-of-a-file

반응형