[英]Linux bash How to use a result of a wildcard as a file name in a copy command
I'm writing a Linux script to copy files from a folder structure in to one folder. 我正在编写一个Linux脚本来将文件从文件夹结构复制到一个文件夹中。 I want to use a varying folder name as the prefix of the file name.
我想使用不同的文件夹名称作为文件名的前缀。
My current script looks like this. 我当前的脚本看起来像这样。 But, I can't seem to find a way to use the folder name from the wildcard as the file name;
但是,我似乎无法找到一种方法来使用通配符中的文件夹名称作为文件名;
for f in /usr/share/storage/*/log/myfile.log*; do cp "$f" /myhome/docs/log/myfile.log; done
My existing folder structure/files as follows and I want the files copied as; 我现有的文件夹结构/文件如下,我希望将文件复制为;
>/usr/share/storage/100/log/myfile.log --> /myhome/docs/log/100.log
>/usr/share/storage/100/log/myfile.log.1 --> /myhome/docs/log/100.log.1
>/usr/share/storage/102/log/myfile.log --> /myhome/docs/log/102.log
>/usr/share/storage/103/log/myfile.log --> /myhome/docs/log/103.log
>/usr/share/storage/103/log/myfile.log.1 --> /myhome/docs/log/103.log.1
>/usr/share/storage/103/log/myfile.log.2 --> /myhome/docs/log/103.log.2
You could use a regular expression match to extract the desired component, but it is probably easier to simply change to /usr/share/storage
so that the desired component is always the first one on the path. 您可以使用正则表达式匹配来提取所需的组件,但是简单地更改为
/usr/share/storage
可能更容易,因此所需的组件始终是路径中的第一个组件。
Once you do that, it's a simple matter of using various parameter expansion operators to extract the parts of paths and file names that you want to use. 一旦你这样做,使用各种参数扩展操作符来提取你想要使用的路径和文件名的部分是一件简单的事情。
cd /usr/share/storage
for f in */log/myfile.log*; do
pfx=${f%%/*} # 100, 102, etc
dest=$(basename "$f")
dest=$pfx.${dest#*.}
cp -- "$f" /myhome/docs/log/"$pfx.${dest#*.}"
done
One option is to wrap the for loop in another loop: 一种选择是将for循环包装在另一个循环中:
for d in /usr/share/storage/*; do
dir="$(basename "$d")"
for f in "$d"/log/myfile.log*; do
file="$(basename "$f")"
# test we found a file - glob might fail
[ -f "$f" ] && cp "$f" /home/docs/log/"${dir}.${file}"
done
done
for f in /usr/share/storage/*/log/myfile.log*; do cp "$f" "$(echo $f | sed -re 's%^/usr/share/storage/([^/]*)/log/myfile(\.log.*)$%/myhome/docs/log/\1\2%')"; done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.