是否有一种简单的方法可以打印file.txt的完整路径?

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

<命令>

dir> <command> file.txt  

应该打印

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

当前回答

我很惊讶居然没人提到定位。

如果已经安装了定位包,甚至不需要在感兴趣的文件所在的目录中。

假设我正在寻找一个setenv.sh脚本的完整路径名。这就是找到它的方法。

$ locate setenv.sh
/home/davis/progs/devpost_aws_disaster_response/python/setenv.sh
/home/davis/progs/devpost_aws_disaster_response/webapp/setenv.sh
/home/davis/progs/eb_testy/setenv.sh

注意,在这种情况下它会找到三个脚本,但是如果我只需要一个I 会这样做:

$ locate *testy*setenv.sh
/home/davis/progs/eb_testy/setenv.sh

其他回答

我知道这是一个老问题了,但在这里补充一下信息:

Linux命令,可用于查找命令文件的文件路径。

$ which ls
/bin/ls

这里有一些注意事项;请参见https://www.cyberciti.biz/faq/how-do-i-find-the-path-to-a-command-file/。

下面的方法通常可以达到目的:

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

使用指向:

readlink -f file.txt

您可以使用此功能。如果给出的文件名没有相对路径,则假定它在当前工作目录中:

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} \'
}