0

I have a postgres db with a table named data. as an example this table contains 6 entires where 3 are erroneous:

data
-----------------
foo/bar/file1.txt
foo/bar/file2.txt
file3.txt
foo/bar/file4.txt
file5.txt
file6.txt

I am looking for a way to strip the 3 files with extra path such that the output becomes:

data
-----------------
file1.txt
file2.txt
file3.txt
file4.txt
file5.txt
file6.txt

SUBSTRING(file_name, 50,70) I can select the right result, but I cant exactly figure out how I rename them in my table: SELECT substring(data, 9, 100) FROM db WHERE data LIKE 'foo/bar%';

2
  • Do you want to change the data in the table? Or just display it differently? Commented Feb 20, 2019 at 10:07
  • I want it changed in the table Commented Feb 20, 2019 at 10:10

3 Answers 3

3

You probably want an UPDATE. Also, better use SUBSTRING(file_name from 'foo/bar/(.*)$') instead of relying on character length. This can help you to reuse the query just by changing the pattern and not counting the length.

UPDATE data SET file_name =  SUBSTRING(file_name from 'foo/bar/(.*)$')
where file_name LIKE 'foo/bar%';

Demo

Sign up to request clarification or add additional context in comments.

Comments

2

You can convert the value into an array and then pick the last entry of that array. That way you don't need to hardcode the file paths in the update statement:

update the_table 
   set data = (string_to_array(data, '/'))[cardinality(string_to_array(data, '/'))]
where strpos(file_name , '/') > 0

Comments

1

This is one one way to get the last item after /:

UPDATE *my_table* SET data =
    (string_to_array(data, '/'))[array_length(string_to_array(data, '/'), 1)];

So convert to array the second convert is to get the size of that array to have the last index.

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.