How can I get only the filename using sed? I've this
out_file=$(echo $in_file|sed "s/\(.*\.\).*/\1mp4/g")
But I get the path too
/root/video.mp4, and I want only
If you already know the extension of the file, you can invoke
Or another option would be cutting everything after the last dot using
Use any of the followings ways:
ps. You get the same string because in your statement
To get the only filename without extension you can :
One of the fundamentals of using regex is that patterns are greedy by nature when specifying the wild card. While the answer proposed by @uloBasEI is certainly a working answer, it also requires the use of the basename command. The original question from @Shixons requests a solution using only sed.
Before continuing, it's always helpful to know which version of sed is the target. I'm assuming BSD (as shipped with OSX).
First of all, the pattern proposed in the original question doesn't work because it captures everything from the beginning of the input string up to and including the last dot. Without anchors, this search will swallow up everything from left to right. The "/1" matched pattern, therefore, is everything up to and including the last dot. Even a filename with multiple dots will be swallowed up whole. Not the desired result at all.
The first step is to establish a strategy for identifying patterns. Here, you'd like to get rid of everything to the left of the filename (we'll deal with the extension later):
The search matches from the beginning of the string. It matches a pattern of "/.*" zero or more times and deletes everything afterwards. We print the matched patterns with "\1". We are not searching globally; we are searching from the beginning of the string by specifying the ^ anchor.
We get better clarity by enabling the "-E" option so we don't have to escape parentheses:
So now we have the part on the left. Let's add the part on the right. Note that we need to keep the left part as a pattern because that's how we can specify that it appears zero or more times. All we do now is add a pattern for the part on the right:
We only print out the second match, thereby discarding everything but the filename. But we still need to remove the filename extension.
The "$" at the end is optional.
Finally, to add the new extension you just revise like so:
An additional optimization is to make the first forward slash optional to handle relative paths:
I came across this question by being lazy while looking for a sed pattern to replace basename. I'm working on a stripped system that doesn't have that command installed.
The easiest solution is remove everything until last appearance of