17

Is there possible to create file that is just a sub-sequence of bytes from another file, like a symlink, but referencing only part of the file?

1
  • 4
    Perhaps if you explain the purpose of what you are trying to do, we could suggest a solution.
    – JRT
    Commented Oct 20, 2011 at 8:22

3 Answers 3

17

Yes, it is (somewhat) possible at least on Linux with some limitations.

The method is to create a read-write loop device that maps to a subset of the file.

eg:

# Write some data to a single file
for ((i=0;i<10000;i++)); do
    printf "%7d\n" $i
done >/var/tmp/file

# Use losetup to manage a new loopback device
# The --find option without any arguments to find an available loop device
# The --show will echo what that found device is to stdout
# We capture this to ensure the rest of the script refers to the correct device
NEW_DEV_LOOP=$(sudo losetup --show --verbose --find --show --offset 512 --sizelimit 512 /var/tmp/file)

# This will be something like /dev/loop3 depending on what devices are available
echo "NEW_DEV_LOOP = $NEW_DEV_LOOP"

# Print status
losetup -a

# Show the contents of the file and loop device
head -2 /var/tmp/file
echo ...
tail -2 /var/tmp/file
echo "==="
sudo head -2 "$NEW_DEV_LOOP"
echo ...
sudo tail -2 "$NEW_DEV_LOOP"

# Write to the loop device and show impact on the file
sudo sh -c "printf 'I was here' > '$NEW_DEV_LOOP'"
grep here /var/tmp/file

# Detatch the example loop device
sudo losetup -d "$NEW_DEV_LOOP"

output:

NEW_DEV_LOOP=/dev/loop0
loop device: /dev/loop0
/dev/loop0: [0808]:136392 (/var/tmp/file), offset 512, size 512
      0
      1
...
   9998
   9999
===
     64
     65
...
    126
    127
I was here   65

I believe both the offset and the size must be multiple of a block size (512 bytes).

You probably need to be root to create and access the loop device.

If you need a symlink, you can create one that points to the loop device.

12

No. You must either reference the whole file, or you must copy the part of the file you're interested in.

2

It could be possible (to create a normal symlink pointing to a part of a file) on a filesystem which implements the "file as directory" idea, which appeared--besides other authors--in the plans for reiserfs, but the reiserfs's implementation wasn't liked for the problems the implementation caused.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .