我有以下文件和目录:
/tmp/jj/
/tmp/jj/ese
/tmp/jj/ese/2010
/tmp/jj/ese/2010/test.db
/tmp/jj/dfhdh
/tmp/jj/dfhdh/2010
/tmp/jj/dfhdh/2010/rfdf.db
/tmp/jj/ddfxcg
/tmp/jj/ddfxcg/2010
/tmp/jj/ddfxcg/2010/df.db
/tmp/jj/ddfnghmnhm
/tmp/jj/ddfnghmnhm/2010
/tmp/jj/ddfnghmnhm/2010/sdfs.db我想将所有2010目录重命名为它们的父目录,然后tar所有.db文件.
我试过的是:
#!/bin/bash
if [ $# -ne 1 ]; then
echo "Usage: `basename $0` <absolute-path>"
exit 1
fi
if [ "$(id -u)" != "0" ]; then
echo "This script must be run as root" 1>&2
exit 1
fi
rm /tmp/test
find $1 >> /tmp/test
for line in $(cat /tmp/test)
do
arr=$( (echo $line | awk -F"/" '{for (i = 1; i < NF; i++) if ($i == "2010") print $(i-1)}') )
for index in "${arr[@]}"
do
echo $index #HOW TO WRITE MV COMMAND RATHER THAN ECHO COMMAND?
done
done1)结果是:
ese
dfhdh
ddfxcg
ddfnghmnhm但应该是:
ese
dfhdh
ddfxcg
ddfnghmnhm2)如何将所有2010目录重命名为其父目录?我的意思是如何做(我想在loop中做这件事,因为有大量的dirs):
mv /tmp/jj/ese/2010 /tmp/jj/ese/ese
mv /tmp/jj/dfhdh/2010 /tmp/jj/dfhdh/dfhdh
mv /tmp/jj/ddfxcg/2010 /tmp/jj/ddfxcg/ddfxcg
mv /tmp/jj/ddfnghmnhm/2010 /tmp/jj/ddfnghmnhm/ddfnghmnhm发布于 2014-04-13 16:00:50
这一点应该是接近的:
find "$1" -type d -name 2010 -print |
while IFS= read -r dir
do
parentPath=$(dirname "$dir")
parentDir=$(basename "$parentPath")
echo mv "$dir" "$parentPath/$parentDir"
done测试后删除echo。如果您的dir名称可以包含换行符,那么请查看find的find选项和xargs的-0选项。
发布于 2014-04-13 07:49:16
您可以使用find来确定目录是否包含名为2010的子目录并执行mv。
find /tmp -type d -exec sh -c '[ -d "{}"/2010 ] && mv "{}"/2010 "{}"/$(basename "{}")' -- {} \;我不确定您在这里是否还有其他问题,但这将执行您在问题末尾列出的内容,即:
mv /tmp/jj/ese/2010 /tmp/jj/ese/ese等等..。
发布于 2014-04-13 08:15:37
可以使用grep -P完成
grep -oP '[^/]+(?=/2010)' file
ese
ese
dfhdh
dfhdh
ddfxcg
ddfxcg
ddfnghmnhm
ddfnghmnhmhttps://stackoverflow.com/questions/23040109
复制相似问题