unix command to copy all .h file with modified dir

2019-09-02 13:06发布

Suppose I have a folder structure like:

Libraries\

  • UIToolkit\
    • files\
      • toolkit.h
      • toolkit.c
      • toolkit.resource
  • NetworkLayer\
    • files\
      • network.h
      • network-info.txt

...

I need a command so that I can input the Libraries folder and specify a Output folder then in the Output folder I have:

Output\

  • UIToolkit\
    • toolkit.h
  • NetworkLayer\
    • network.h

Basically it:

  1. copies all .h file and preserves the folder structure
  2. also move all the headers to its sub-libraries' root folders no matter how deep they are in the sub-libraries sub-folders.

I was using rsync but it does not do 2nd step, so I guess I need some quick and dirty modification?

Thanks a lot!

标签: bash shell bsd
2条回答
Evening l夕情丶
2楼-- · 2019-09-02 13:33

A bit modified answer based on devnull's:

idir=$1
odir=$2

while read -r f; do
    subdir=${f#$idir}
    subdir=${subdir%%/*}
    mkdir -p $odir/$subdir
    cp -a $f $odir/$subdir
done < <(find $idir -type f -name "*.h")

call something like

./thisscript.sh Libraries Output

shall be able to work with absolute or relative directories, IMHO; but won't handle if .h file is right under Libraries (must be at least one subdir level down..).

查看更多
▲ chillily
3楼-- · 2019-09-02 13:45

You can say:

cd /path/to/Libraries
while read -r file; do
  odir=$(cut -d'/' -f2 <<< ${file});
  fname=$(basename ${file});
  cp "$file" "/path/to/Output/${odir}/${fname}";
done < <(find . -type f -name "*.h")

This would copy all the *.h files to the Output folder as per the desired directory structure.

查看更多
登录 后发表回答