是否有一种简单的方法可以打印file.txt的完整路径?
file.txt = /nfs/an/disks/jj/home/dir/file.txt
<命令>
dir> <command> file.txt
应该打印
/nfs/an/disks/jj/home/dir/file.txt
是否有一种简单的方法可以打印file.txt的完整路径?
file.txt = /nfs/an/disks/jj/home/dir/file.txt
<命令>
dir> <command> file.txt
应该打印
/nfs/an/disks/jj/home/dir/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
其他回答
我知道这是一个老问题了,但在这里补充一下信息:
Linux命令,可用于查找命令文件的文件路径。
$ which ls
/bin/ls
这里有一些注意事项;请参见https://www.cyberciti.biz/faq/how-do-i-find-the-path-to-a-command-file/。
除了"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 $
这也给出了控制台的完整路径和文件名
跑题:这种方法只给出相对链接,而不是绝对链接。readlink -f命令是正确的。
如果你和文件在同一个目录:
ls "`pwd`/file.txt"
用目标文件名替换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} \'
}
find / -samefile file.txt -print
会发现所有链接的文件与相同的索引节点号为file.txt
添加-xdev标志将避免find跨越设备边界(“挂载点”)。(但是,如果find不是在与file.txt相同的设备上的目录开始,这可能会导致什么也找不到)
请注意,find可以报告单个文件系统对象的多个路径,因为一个Inode可以通过多个目录条目链接,甚至可能使用不同的名称。例如:
find /bin -samefile /bin/gunzip -ls
将输出:
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