I have a string GameOfThronesS01E05.mkv. I want GameOfThronesS01E05 using sed with regex.

I tried

echo GameOfThronesS01E05.mkv | sed 's/\(.+\)\.mkv$/\1/'

and it didn't work

  • 4
    Is there a reason not to use basename GameOfThronesS01E05.mkv .mkv?
    – doneal24
    Feb 10 '17 at 17:17
  • 1
    + is literal in BRE - you need \+ if you want it to be treated as a quantifier. But there are much simpler ways to remove extensions. Feb 10 '17 at 17:18
  • sed -r 's/(.+)\.mkv$/\1/'
    – JJoao
    Feb 10 '17 at 17:32
  • 1
    neckTwi - it doesn't work because you have escaped those chars; run sed -E 's/(.+)\.mkv$/\1/' though there are better ways to do this, even with sed... Feb 10 '17 at 17:41
  • 1
    .+ can always be replaced by ..*.
    – Kusalananda
    Feb 10 '17 at 17:43

If you are using a system that has GNU utilities, you can always use basename to strip the extension:

$ basename -s ".mkv" GameOfThronesS01E05.mkv                                                          

Otherwise, python is always a good choice,too:

$ python -c 'import sys;print sys.argv[1][:-4]' GameOfThronesS01E05.mkv                               

This is a more simpler solution:

echo GameOfThronesS01E05.mkv | sed -n 's/.mkv//p'
  • I just want to know whats wrong with my expression.
    – Necktwi
    Feb 10 '17 at 17:36
  • why do you need -n and p ? and as a general rule, the dot has to be escaped Feb 10 '17 at 17:48

Thanks @don_crissti. here is my MKV to MP4 converter

$vi /usr/local/bin/MKVtoMP4
for entry in *
        if [[ $entry =~ .+\.mkv$ ]]; then
                FILENAME=`echo $entry | sed -E 's/(.+)\.mkv$/\1/'`
                ffmpeg -i "$entry" -codec copy "${FILENAME}.mp4"
chmod ug+x /usr/local/bin/MKVtoMP4
  • 2
    1. This does not answer your question. 2. You can use ./*.mkv instead of * - that way you can get rid of that if condition 3. You can also get rid of that FILENAME assignment and simply run for entry in ./*.mkv; do ffmpeg -i "$entry" -codec copy "${entry%.*}.mp4"; done - so one line of code instead of seven... Feb 10 '17 at 17:57
  • thats embarrassing. lost all the triumph
    – Necktwi
    Feb 10 '17 at 18:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.