2

I want to extract information from file path and use it as part of substitute string, racked my mind, tried many times and only to found the follwing works

let spd = split(expand('%:p'),"/")
%s/to_be_replaced/\=spd[-2]/g

I want to merge the two commands into one

%s/to_be_replaced/\=split(expand('%:p',"/"))[-2]/g

but it doesn't work. Since I am working with multiple files in tab mode, the two commmands method is actually quite inconvenient. Moreover, it doesn't fulfill the requirement since

%s/to_be_replaced/some_string\=spd[-2]more_string/g

is also wrong. So I am wondering if there is a solution or a quicker way to do it?

2 Answers 2

3

Try other delimit (such as @)

%s@to_be_replaced@\=split(expand('%:p'),'/')[-2]@g

If you want to embed expr insider string:

%s@to_be_replaced@\=printf('some_string%smore_string', spd[-2])@g
Sign up to request clarification or add additional context in comments.

Comments

0

Alternative

Unless you invoke this for multiple buffers (:bufdo et al.), your expression is constant for the buffer. You can therefore insert it literally in the command line via <C-r>=:

:%s/to_be_replaced/<C-r>=split(expand('%:p'),"/")[-2]<CR>/g

Explanation of your problem

The reason why your original attempt doesn't work is explained at :help sub-replace-expression:

Be careful: The separation character must not appear in the expression! Consider using a character like "@" or ":".

As kev has pointed out, you can just use any other single-byte character, but not an alphanumeric character, '\', '"' or '|'.

1 Comment

Thank you for your nice reply!

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.