tags:

views:

45

answers:

1

i have some old php files which i'd like to convert to use gettext. those files have a content like this :

$LD = 'Some String';
$Another = 'some other ~n~ string';

i have to substitute all the $LD, $Another in the files where they are declared with something like :

_('Some string');

hacking a bit a created some sort of regexp to find the declarations, my aim was to use sed and awk to do the replaces..but i don't have any clue on how to do those substitutions ...

any help ...

A: 

Try this:

sed -r $'s/(\$LD = )(\'.*\')(.*)/\\1_(\\2)\\3/' filename

Example:

$ echo "\$LD = 'Some String';" | sed -r $'s/(\$LD = )(\'.*\')(.*)/\\1_(\\2)\\3/'
$LD = _('Some String');

Edit:

This will look for and change both variables, the -i will make the change in-place:

sed -i -r $'s/(\$(LD|Another) = )(\'.*\')(.*)/\\1_(\\3)\\4/'

You can list more variable names separated by pipe characters.

Your grep command needs single quotes instead of backticks and a -E to use extended regexes. It also needs a filespec glob. The regex as you have basically says "Does this file have any variable definitions?" It says to look for any variable that:

  • starts at the beginning of the line with no whitespace before it
  • has zero or more array subscripts consisting of zero or more digits (which would include a null subscript, thus an array append)
  • ignore any associative array assignments ($array["key"]=value)
  • the line must end in a semicolon
  • I'm not sure what the ? is intended to do

This fails if the variable assignment:

  • occurs after some whitespace
  • uses an alpha key or a variable as a key
  • occurs on a line with other statements
  • has any trailing whitespace
  • possibly others

You might need to make your regex more robust or simpler or just assume that any PHP file will have a variable assignment and let sed look for and change just the variables of interest.

In order for your grep to have files to process, you need to specify which files to look at:

grep -E -i -R 'your regex' * | sed ...

Or, if you let sed do it:

find . -name "*.php" | sed ...

Also, a tool called ack is better than grep for finding stuff in code files.

In any case, especially if you use the in-place option, I strongly recommend test runs (and backups).

Dennis Williamson
so for looking in multiple files and doing a replace i'd need something like :grep -i -R `^\$\w+\s*(\[[0-9]*\])*\s*=\s*.*?;$` | sed -r $'s/(\$LD = )(\'.*\')(.*)/\\1_(\\2)\\3/'
Gjergj Sheldija
thank you very much :)
Gjergj Sheldija