tags:

views:

39

answers:

3

I have a .sql file that needs a little tweaking, speficially:

[xx_blah]

any pattern like the above needs to be changed to:

[Blah]

i.e. remove the xx_prefix and upper case the next character.

any tips?

+3  A: 

Simple blah replacement:

$ sed -e 's/\[[^]]*_blah]/[Blah]/g' old.sql > new.sql

More general:

$ perl -pe 's/\[[^]_]+_(.+?)]/[\u$1]/g' old.sql > new.sql

The reason to match the prefix with [^]_]+ rather than .+ is regular-expression quantifiers are greedy. For example, the latter when given [xx_blah][xx_blah] as input would gobble up as much as possible and match xx_blah][xx, not what you intended. Excluding right bracket and underscore is a safety stop.

The \u in the replacement is an escape sequence that uppercases the following letter.

If you prefer sed and your eyes don't get crossed from all the backslashes, go with

$ sed -e 's/\[[^]_]\+_\(.\+\?\)]/[\u\1]/g' old.sql > new.sql
Greg Bacon
none of these seemed to work? could it be because the file was created on a windows machine? (spacing? tabs? newline?)
mrblah
Was the output of `diff -ub old.sql new.sql` empty?
Greg Bacon
+1  A: 
sed -e 's/xx_\([a-z]\)/\u\1/' < old.sql > new.sql
Mez
tried this, the file didn't change at all.
mrblah
Well, that depends on whether you ACTUALLY meant xx_
Mez
A: 

you can just use the shell without external tools

#!/bin/bash
declare -a arr
while read -r -a arr
do
    for((i=0;i<=${#arr};i++))                    
    do
        case "${arr[i]}" in
            *"[xx_"* );;&
            *"["*)
                arr[i]=${arr[i]//xx_/}
                arr[i]=${arr[i]^^${arr[i]:1:1}}
        esac
    done
    echo ${arr[@]}
done < "file"

example of output when run

PS1> more file
this is first line
this is second line
[xx_blah]
this is fourth line
blah [xx_blah] blah [xx_blah]
[someText]
end

PS1> ./mychanger.sh
this is first line
this is second line
[Blah]
this is fourth line
blah [Blah] blah [Blah]
[SomeText]
end