AndreaCioccarelli AndreaCioccarelli - 1 month ago 6
Linux Question

Bash: find and replace text from a script

Today i want to ask a very difficult question: I need to modify a number into a file, via terminal emulator.
I cannot use busy box or others UNIX-BASED Utilities.

the file is called build.prop and I must remove a line that contains

dalvik.vm.heapsize=256
and replace it with a new line that contains
dalvik.vm.heapsize=512
. I not know the line number and 256 is an ipotetic value. How I can build a script that perform this action??

Answer

Use the sed command:

sed -i -e 's/^\(dalvik.vm.heapsize=\).*/\1512/' build.prop

The command searches for a line starting with dalvik.vm.heapsize=, then replaces the part after = with 512. The left part is captured using the regular expression group, and \1 in the replacement part (\1512) refers to this group. The -i option instructs to replace in-place. Refer to info sed for details.

Here is a more advanced example taking into account possible leading spaces/tabs and making the match stricter by means of the regular expression lists:

sed -i -e 's/^\([ \t]*dalvik.vm.heapsize=\)[0-9]\+/\1512/' build.prop

Perl is more flexible. I prefer to use it for more complicated tasks. There is no such simple way as sed's -i option for Perl, however; but you can simply use the shell redirection, e.g.:

cat build.prop | \
  perl -n -e 's/^([\t\s]*dalvik.vm.heapsize=)\d+/${1}512/; print' > build.prop
Comments