0

Friends,

I'm trying to generate dynamic sql script and replace string from the original query result.

Original: '/u02/DB/FILE/file01.dbf' or 
Original: '+DATA/DB/FILE/file01.dbf'

Required : '/u01/data/dbname/file01.dbf'
  1. Start search from 2nd character from original, find 1st and 2nd appearance of '/' and replace with data (hopefully this covers both original scenario)
  2. Start search from 2nd character from original, find 2nd and 3rd appearance of '/' and replace with dbname

DB and FILE in original could be any location so can't really hardcode that.

I use below to replace FILE with dbname but that's not helping totally,

Somehow feels approach is too complex and there should be better/diferent way.

    SELECT 'alter database rename file ''' || f.file_name || ''' to '''|| '/u01' ||
          REGEXP_REPLACE(SUBSTR(f.file_name, INSTR(f.file_name, '/',2)), '/FILE/', '/dbname/', 1||''';' stmt
    FROM ( SELECT name file_name, bytes
             FROM v$tempfile
             ORDER BY bytes ESC
         )f;

Thanks and much appreciated.

6
  • 1
    Try something like regexp_replace('/u02/DB/FILE/file01.dbf', '^([^/]*/[^/]*/)[^/]*/[^/]*', '\1data/dbname'). Commented May 26, 2017 at 20:30
  • WOW, that was super quick, looks like it's working as expected, will test completely and confirm. Commented May 26, 2017 at 20:39
  • @WiktorStribiżew it worked perfectly, how can we edit it slightly to search from 2nd character to avoid +DATA? Commented May 26, 2017 at 20:49
  • Sorry, I am not getting that: you should just use ^ to match the start of string, then [^/]* to match 0+ chars other than / and then / - that will be the first /, then add [^/]* to get to the 2nd /. Commented May 26, 2017 at 21:04
  • Sorry if I was not able to explain it properly, provided solution works if string starts with '/' but if original starts with +DATA then we don't get correct result. so trying to start search of '/' from 2nd character of the original string. Commented May 26, 2017 at 21:13

1 Answer 1

3

You may use a single regex replace operation with:

^([^/]*/[^/]*/)[^/]*/[^/]*

Replace with \1data/dbname.

Details

  • ^ - match start of a string
  • ([^/]*/[^/]*/) - Group 1 (referred to with \1 backreference from the replacement pattern):
    • [^/]* - 0+ chars other than /
    • / - a slash
    • [^/]* - 0+ chars other than /
    • / - a slash
  • [^/]* - 0+ chars other than /
  • / - a slash
  • [^/]* - 0+ chars other than /

A quick online test:

select regexp_replace('/u02/DB/FILE/file01.dbf', '^([^/]*/[^/]*/)[^/]*/[^/]*', '\1data/dbname') AS RESULT from dual
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.