我有以下文件和目录:
/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
done
1)结果是:
ese
dfhdh
ddfxcg
ddfnghmnhm
但它应该是:
ese
dfhdh
ddfxcg
ddfnghmnhm
2)如何将所有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
答案 0 :(得分:2)
您可以使用find
来确定目录是否包含名为2010
的子目录并执行mv
:
find /tmp -type d -exec sh -c '[ -d "{}"/2010 ] && mv "{}"/2010 "{}"/$(basename "{}")' -- {} \;
我不确定你在这里是否有任何其他问题,但这会做你在问题末尾列出的内容,即它会:
mv /tmp/jj/ese/2010 /tmp/jj/ese/ese
依旧......
答案 1 :(得分:2)
可以使用grep -P
完成:
grep -oP '[^/]+(?=/2010)' file
ese
ese
dfhdh
dfhdh
ddfxcg
ddfxcg
ddfnghmnhm
ddfnghmnhm
答案 2 :(得分:1)
首先,只遍历您感兴趣的目录,并避免使用临时文件:
for d in $(find $1 -type d -name '2010') ; do
然后,您可以使用basename
和dirname
来提取该目录名称的部分内容并重新构建所需目录名称。类似的东西:
b="$(dirname $d)"
p="$(basename $b)"
echo mv "$d" "$b/$p"
您可以使用shell字符串替换操作而不是basename / dirname。
答案 3 :(得分:1)
这应该是关闭的:
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
。如果您的目录名称可以包含换行符,请查看-print0
的{{1}}选项和find
的{{1}}选项。