是否有一种简单的方法可以打印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
当前回答
这可以简化
ls <file_name> | pwd
其他回答
另一个Linux实用程序,它做这个工作:
fname <file>
这很天真,但是我必须使它与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}
我发现最简单的方法是:
for i in `ls`; do echo "`pwd`/$i"; done
这对我来说很有效。
如果你和文件在同一个目录:
ls "`pwd`/file.txt"
用目标文件名替换file.txt。
echo $(cd $(dirname "$1") && pwd -P)/$(basename "$1")
这是对@ZeRemz的答案的解释:
这个脚本获取相对路径作为参数"$1" 然后我们得到该路径的dirname部分(你可以将dir或file传递给这个脚本): 然后将“$(dirname“$1”)cd到这个相对目录中 && pwd -P并获取它的绝对路径。-P选项将避免所有符号链接 在此之后,我们将basename附加到绝对路径: 作为最后一步,我们重复它