Category Archives: Linux General

Notes which apply to all flavours of Linux systems

Search and replace in vi (or sed)

Search and replace in vi is both quick and simple:

X,Ys/search/replace/g

(where x – start line number, y – end line number. optional)

One very useful feature is the ability to use parts of the search regular expression within the replace string.

For example, where the selected lines contain values between 2000-2999 and all these values need to be increased by 1000 so that all the values are now in range 3000-3999:

X,Ys/2\([0-9][0-9][0-9]\)/3\1/g

The \1 includes the contents of the 1st regular expression delimited by ( ).

Multiple regular expressions can be reproduced in the replace string. For example, in the file containing:

Surname, Forename
surname, forename

The command:

1,2s/\([a-z]*\), \([a-z]*\)/\2 \1/ig

Results with:

Forename Surname
forename surname

\2 in the replacement string matches the 2nd regular expression in the search string, and likewise for \1 with the 1st regular expression.

View ‘dd’ progress

When reading/writing a disk image using Linux tool ‘dd’ launch as follows:
dd if=/dev/sdb of=filename.img & pid=$!
this will run ‘dd’ in the background.

To see the progress:
kill -USR1 $pid
(it will not kill the dd)

Notes:

  1. If you are doing it as a non-root user you’ll need to prefix those commands with sudo
  2. If you do that do ‘sudo ls‘ first, otherwise the ‘sudo dd‘ will fail waiting on the password which it’ll never get as its backgrounded.

Thanks to Cian.

Exporting physical Linux hard disk to a Virtual Machine

Shutdown and remove the hard disk, then connect to a separate PC with VirtualBox (virtualbox-ose) installed.

  • Take a ‘dd’ copy of the hard disk, eg: dd if=/dev/sdb of=filename.img
    (warning this may take a while and requires enough free disk space to hold a copy of the entire hard disk being cloned)
  • After the image has been successfully created, convert it to an image suitable for VMWare or VirtualBox using the command:
    vboxmanage convertfromraw filename.img -format VMDK filename.vmdk
  • This can be imported into VirtualBox by creating a new (Linux/Other Linux) Virtual Machine and “Use existing hard drive”. Click the browse button to go to the Virtual Media Manager, click ‘Add’ and select the VMDK file created in the previous step.

The virtual machine should now be ready to run in VirtualBox.
To import into VMWare, create a new virtual machine and virtual hard disk. Overwrite the new Virtual Hard disk by copying the VMDK file created earlier, into its place.