我使用readlink查找文件的完整路径:
cek=$(readlink -f "$1")
mkdir -p "$ydk$cek"
mv "$1" "$ydk/$cek/$ydkfile" 但readlink -f "$1"给了我一条完整的道路。我怎么才能剪出完整的路径呢?
例如:
/home/test/test/2014/10/13/log.file但我需要
/test/2014/10/13/我该怎么做呢?
从多个评论来看:
readlink返回的完整路径的最后四个目录组件。给予:
full_path=/home/some/where/hidden/test/2014/08/29/sparefile.log产出应是:
test/2014/08/29(不要在路径修整代码中构建任何关于今天日期的假设。)
发布于 2014-10-13 14:36:37
如果您需要完整路径的最后四个目录组件,并且在完整路径中没有换行符,如果您拥有支持grep的GNU grep或BSD (Mac OS X) grep(仅输出匹配的材料),那么这将提供所需的结果:
$ cek="/home/test/test/2014/10/13/log.file"
$ echo "${cek%/*}"
/home/test/test/2014/10/13
$ echo "${cek%/*}" | grep -o -E -e '(/[^/]+){4}$'
/test/2014/10/13
$ full_path=/home/some/where/hidden/test/2014/08/29/sparefile.log
$ echo "${full_path%/*}" | grep -o -E -e '(/[^/]+){4}$'
/test/2014/08/29
$我需要路径启动
/201[0-9]:/home/bla/bla2/bla3/2014/01/13/13…⟶/2014/01/13/13….
因此,您需要再次使用grep -o,从年份模式开始:
echo "${fullpath%/*}" | grep -o -e '/201[0-9]/.*$'这要简单得多;您甚至不需要扩展正则表达式!
如果在一年前也需要path元素,那么需要:
echo "{fullpath%/*}" | grep -o -e '/[^/][^/]*/201[0-9]/.*$'发布于 2014-10-13 14:06:15
你真的需要删除"/home“吗?
cek="/home/test/test/2014/10/13/log.file"
dir=$(dirname "$cek")
echo "${dir#/home}"/test/test/2014/10/13仅最后4个目录组件:
last4dirs() {
local IFS=/
local -a components=($1)
local l=${#components[@]}
echo "${components[*]:l-5:4}"
}
last4dirs /home/some/where/hidden/test/2014/08/29/sparefile.logtest/2014/08/29https://stackoverflow.com/questions/26341845
复制相似问题