Move files while making a tar

I have the following folder structure

code/f1/
code/lib/t1
code/lib/t2
code/lib/t3
code/lib/t3
code/lib_1/t1
code/exc

I would like to create a tar with a folder structure below and I can use the following tar command
f1
lib/t1
lib/t2
lib/t3

tar -cvf code.tar -C code f1 lib --exclude exc lib_1

But in some cases I need to replace lib/t1 with lib_1/t1 and keep the folder structure lib/t1.
I would like to know Is there a way in tar command I can move/replace an existing file in a tar with a different file but keep the existing folder structure?
or Add a file to a tar with a specific folder path?
or Move files during tar?

Thanks for the help in advance!

Do those subfolders contain any symbolic links? If not, what I would do is create a directory skeleton to arrange however I please, with symlinks to the actual targets, then tar it up with -h (to follow symlinks, instead of storing them as symlinks).

i.e.

mkdir -p tardir/lib
# assumes code is in the CURRENT directory.
# One way to make t1
# ln -s ../../code/lib_1/t1 tardir/lib/t1

# Other way
ln -s ../../code/lib/t1 tardir/lib/t1

# the rest
ln -s ../../code/lib/t2 tardir/lib/t2
ln -s ../../code/lib/t3 tardir/lib/t3
ln -s ../code/exc tardir/exc

tar -hcf /path/to/file.tar -C tardir .
1 Like

Thanks Corona688!

ln -s ../../code/lib_1/t1 tardir/lib/t1
Would you please explain me why I have to go two level back even though code is in my present working directory?
ln -s ../code/exc tardir/exc
And I only need to go back one level to include a directory?

Because the path is relative to the link's folder, not the current one. If the link you're creating is buried two folders deep, the base path you're trying to reach from it is two folders back out.

You could just use /absolute/paths to avoid all that doublethink. In fact, that's probably a better idea now that I think about it.

1 Like