سؤال

Suppose I have the following directories and files

inc:
inc/foo.h
inc/bar.h
inc/more.h
src:
src/foo.cc
src/bar.cc
src/more.cc

and I want to generate a tape archive using tar which contains some of those files (all with foo or bar in their name), but as if they are all in one single directory. Thus, after unpacking via tar -xf archive.tar my archive somewhere, I have

somewhere/foo.h
somewhere/bar.h
somewhere/foo.cc
somewhere/bar.cc

Can I do that just with tar and without moving/copying my files? How?

هل كانت مفيدة؟

المحلول

Using GNU tar and tar --help:

File name transformations:

  • --strip-components=NUMBER
    strip NUMBER leading components from file names on extraction

  • --transform=EXPRESSION, --xform=EXPRESSION
    use sed replace EXPRESSION to transform file names

On the face of it, therefore, you use it at extract time:

tar -xf filename.tar --strip-components=1 -C somewhere

The -C somewhere changes directory to somewhere before extracting files.


Since you know about the --strip-components option but it doesn't meet your requirements, the next option to try is --transform. Since you want to remove all leading components of the path, then the expression can be quite simple:

tar -cf filename.tar --transform='s%.*/%%' .

This seems to work; I tested it using:

$ mkdir junk
$ cd junk
$ mkdir inc src
$ for file in inc/foo.h inc/bar.h inc/more.h src/foo.cc src/bar.cc more.cc; do cp ../makefile $file; done
$ tar -cf - --transform='s%.*/%%' . | tar -tvf -
drwxr-x--- jleffler/eng      0 2014-05-06 10:00 ./
-rw-r----- jleffler/eng   1183 2014-05-06 10:00 more.cc
drwxr-x--- jleffler/eng      0 2014-05-06 10:00 inc/
-rw-r----- jleffler/eng   1183 2014-05-06 10:00 more.h
-rw-r----- jleffler/eng   1183 2014-05-06 10:00 bar.h
-rw-r----- jleffler/eng   1183 2014-05-06 10:00 foo.h
drwxr-x--- jleffler/eng      0 2014-05-06 10:00 src/
-rw-r----- jleffler/eng   1183 2014-05-06 10:00 bar.cc
-rw-r----- jleffler/eng   1183 2014-05-06 10:00 foo.cc
$
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top