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

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

<命令>

dir> <command> file.txt  

应该打印

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

当前回答

在Mac OSX中,执行以下步骤:

CD到目标文件的目录。 输入下列任意一个终端命令。

Terminal
ls "`pwd`/file.txt"
echo $(pwd)/file.txt

用实际的文件名替换file.txt。 按回车键

其他回答

在类似的场景中,我从其他位置启动cshell脚本。为了设置脚本的正确绝对路径,让它只在指定的目录中运行,我使用了以下代码:

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

$0存储脚本执行的确切字符串。

例如,如果脚本像这样启动:$> ../../test/test.csh, $script_dir将包含/home/abc/sandbox/v1/

在mac下面提到的行工作。不需要添加任何花哨的线条。

> pwd filename

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

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

我猜你用的是Linux。

我在coreutils 8.15中找到了一个名为realpath的实用程序。

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

由于问题是关于如何获取文件的完整/绝对路径,而不是关于如何获取符号链接的目标,请使用-s或——no-symlinks,这意味着不要展开符号链接。

根据@styrofoam-fly和@arch-standton注释,realpath本身并不检查文件是否存在,为了解决这个问题,添加e参数:realpath -e file

我知道有一个更简单的方法,但如果我能找到它…

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