Convert multiple Flash (flv) Videos to, for example, MPEG encoding

With ffmpeg and bash this is really easy. Also .flv and .mpeg are easily interchangeable by all other video codecs supported by ffmpeg:

#!/bin/bash
##convert all videos of $srctype type to $desttype type encoding
SRCCODEC="flv"
DESTCODEC="mpeg"
for i in *.$SRCCODEC; do
    echo
    echo -n "###################  "
    echo -n "will convert \"$i\""
    echo "  ###################"
    echo
    ffmpeg -i "${i}" -y "${i%%.${SRCCODEC}}.${DESTCODEC}" && rm -vf "$i"
done

Note that this includes removing the original video file only after a successful recode run overwriting existing destination files (-y option). The interesting part is this: ${i%%.${SRCCODEC}}. It removes the source’s postfix, i.e. file extension. You could save this as a text file, say convert_all_videos_in_pwd.sh and chmod +x filename. I have my own scripts go to ~/bin which I include in $PATH via ~/.bashrc. If you do so you would typically call this within the videos’ directory including logging all output and errors to convert.log, i.e. redirecting STDOUT (= file descriptor 1) and STDERR (= file descriptor 2) via &>:

convert_all_videos_in_pwd.sh &> convert_all.log &

If you want to see the output you could use tail -f logfile or read more on redirection and duplication. You could also do all that in a single command line:

for i in *.flv; do echo converting $i; ffmpeg -i "${i}" -y "${i%%.flv}.mpeg" && rm -vf "$i"; done

Learn Python in 100 Python Session Log Lines: A Python Demo

Well, not exactly 100, but sort of 😉 For a quick and dirty overlook to learn python from (valid) source code:

>>> myvar = 3
>>> myvar += 2 # no myvar++
>>> myvar -= 1
"""This is a multiline comment.
The following lines concatenate the two strings."""
>>> mystring = "Hello"
# Concatenate strings:
>>> mystring += " world."
>>> print mystring
Hello world.
# This swaps the variables in one line(!).
>> myvar, mystring = mystring, myvar
# List with number, list, tupel as elements:
>>> sample = [1, ["another", "list"], ("a", "tuple")]
# List with string, int, float as elements:
>>> mylist = ["List item 1", 2, 3.14]
# Change first element:
>>> mylist[0] = "List item 1 again"
# Dereference the last element (second last would be -2):
>>> mylist[-1] = 3.14
# Dictionary; known as hash in perl:
>>> mydict = {"Key 1": "Value 1", 2: 3, "pi": 3.14}
>>> mydict["pi"] = 3.15
# Tupel a.k.a. int array:
>>> mytuple = (1, 2, 3)
# Pointer to function len:
>>> myfunction = len
>>> print myfunction(mylist)
3
>>> mylist = ["List item 1", 2, 3.14]
# List ranges, called slicing. Range = [a, b):
>>> print mylist[:]
['List item 1', 2, 3.1400000000000001]
>>> print mylist[0:2]
['List item 1', 2]
>>> print mylist[-3:-1]
['List item 1', 2]
>>> print mylist[1:]
[2, 3.14]
>>> print "He said 'hello'."
He said 'hello'.
>>> print 'He said "hello".'
He said "hello".
>>> unicodestring =  u"This is a unicode string"
>>> strString = """This is
>>> a multiline
>>> string."""
""" %s get replaced with items from a given tuple | dict,
left to right (borrowed from printf()):"""
>>>print "Name: %s\nNumber: %s\nString: %s" % (myclass.name, 3, 3 * "-")
Name: Poromenos
Number: 3
String: ---
""" % is a string creation operator. Watch out for the
trailing s in "%(key)s", like printf's modifiers:"""
>>> print "This %(verb)s a %(noun)s." % {"noun": "test", "verb": "is"}
This is a test.
# If you prefer C syntax just define your own function
# ('*' means to wrap parameters up in a tuple and ',' adds no \n):
def printf(format, params): print format % params,
"""controling flow by if, for, while. Use if instead of case/switch.
Blocks are marked by indention!"""
rangelist = range(10)
>>> print rangelist
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for number in rangelist:
    # Check if number is one of
    # the numbers in the tuple.
    if number in (3, 4, 7, 9):
        # "Break" terminates a for without
        # executing the "else" clause.
        break
    else:
        # "Continue" starts the next iteration
        # of the loop. It's rather useless here,
        # as it's the last statement of the loop.
        continue
else:
    # The "else" clause is optional and is
    # executed only if the loop didn't "break".
    pass # Do nothing

if rangelist[1] == 2:
    print "The second item (lists are 0-based) is 2"
elif rangelist[1] == 3:
    print "The second item (lists are 0-based) is 3"
else:
    print "Dunno"
while rangelist[1] == 1:
    pass
# Declare functions with def; optional arguments have default value assigned:
def myfunction(arg1, arg2 = 100, arg3 = "test"):
    # multiple returns, i.e. multidimentional function.
    # '\' is line continuation character:
    return arg3, \
    arg2, arg1
>>>ret1, ret2, ret3 = myfunction("Argument 1", arg3 = "Named argument")
# notice = doing a multi-assignement here!
>>>print ret1, ret2, ret3
Named argument 100 Argument 1
# We can do easy value swapping:
>>>ret1, ret3 = ret3, ret1
>>>print ret1, ret3
Argument 1 Named argument
# Same as def f(x): return x + 1 but without a function's name:
functionvar = lambda x: x + 1
>>> print functionvar(1)
2
# Private vars and methods start by >= 2 underscores and
# <2 ones ppended (by convention only). __spam is
# replaced by _classname__spam literally.
# __init__() is the closest python gets to a constructor
# (instance already exists when it's called:
class MyClass:
    common = 10
    def __init__(self, n=3):
        self.myvariable = n
    def myfunction(self, arg1, arg2):
        return self.myvariable
# Initiate:
>>> instance = MyClass()
>>> instance.myfunction(1, 2)
3
>>> instance2 = MyClass()
# variable 'common' is shared by all instances via their class:
>>> instance.common
10
>>> instance2.common
10
# Note how we use the class name instead of the instance:
>>> MyClass.common = 30
>>> instance.common
30
>>> instance2.common
30
# by explicitly declaring a value it becomes
# an instance variable (called data attribute):
>>> instance.common = 10
>>> instance.common
10
>>> instance2.common
30
>>> MyClass.common = 50
# This doesn't chance this:
>>> instance.common
10
# but this
>>> instance2.common
50
# This class inherits from MyClass which is just a special
# case for multiple inheritance as in
# class OtherClass(MyClass1, MyClass2, ..., MyClassN)
class OtherClass(MyClass):
    def __init__(self, arg1):
        self.myvariable = 3
        print arg1
>>> instance = OtherClass("hello")
hello
>>> instance.myfunction(1, 2)
3
# Add (instance) members 'on-the-fly':
>>> instance.test = 10
>>> instance.test
10
# this throws an error
>>> instance2.test
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: MyClass instance has no attribute 'test'
def somefunction():
    try:
        # Division by zero raises an exception
        10 / 0
    except ZeroDivisionError:
        print "Oops, invalid."
    else:
        # Exception didn't occur, we're fine.
        pass
>>> fnExcept()
Oops, invalid.
# Import external libraries:
import random
# This will instead import the desired function only:
from random import randint
randomint = random.randint(1, 100)
>>> print randomint
42
# convert data structures to strings using prickle library.
import pickle
mylist = ["This", "is", 4, 13327]
# Open C:\binary.dat for writing. 'r' prevents backslash escaping:
myfile = file(r"C:\binary.dat", "w")
pickle.dump(mylist, myfile)
myfile.close()
#remove, i.e. free, variable. works on list items, too:
del mylist
myfile = file(r"C:\text.txt", "w")
myfile.write("This is a sample string")
myfile.close()
myfile = file(r"C:\text.txt")
>>> print myfile.read()
'This is a sample string'
myfile.close()
# Open the file for reading.
myfile = file(r"C:\binary.dat")
loadedlist = pickle.load(myfile)
myfile.close()
>>> print loadedlist
['This', 'is', 4, 13327]
# some hints:
# chain conditions (a must be 2):
1 < a < 3
# list comprehensions are powerfull:
>>> lst1 = [1, 2, 3]
>>> lst2 = [3, 4, 5]
>>> print [x * y for x in lst1 for y in lst2]
[3, 4, 5, 6, 8, 10, 9, 12, 15]
>>> print [x for x in lst1 if 4 > x > 1]
[2, 3]
# "any" returns true if any item in the list is true.
>>> any(i % 3 for i in [3, 3, 4, 4, 3])
True
# Check how many items have this property.
>>> sum(1 for i in [3, 3, 4, 4, 3] if i == 3)
3
>>> del lst1[0]
>>> print lst1
[2, 3]
# variables outside functions are global but need to be pointed out for writing:
number = 5
def myfunc():
    # This will print 5.
    print number
def anotherfunc():
    # This raises an exception because the variable has not
    # been assigned to before printing. Python knows that it a
    # value will be assigned to it later and creates a new, local
    # number instead of accessing the global one.
    print number
    number = 3
def yetanotherfunc():
    global number
    # This will correctly change the global.
    number = 3

As with any language, even natural ones, you need to practice it for a longer while to really get to know it. So what are you waiting for? Dive into Python, now! 😉

References and Further Reading:

Essential and Handy Commands for the Text Editor vi (vim)

If for a key combination, something like nx, the n is missing one is assumed. E.g. to replace only a single character right under the cursor position in normal mode hit s followed by the replacement (can be more characters but only the first will be replaced). For most commands the optional number right before the command is somewhat a repeater to instruct how often the following should be executed.

Essentials

insert at cursor i
insert at start of line I
.. end of line A
leave insert mode <ESC>
replace next (n) char(s) incl. cursor ns
repeat last (n) command(s) n.
insert n new lines after this no
insert n new lines before this nO
delete next n lines with current ndd
delete until end of line D
paste from cursor onwards nP
past after cursor np

Search and Replace

  1. Change to normal (navigation) mode with <ESC>
  2. Search (Wraped around at end of file):
    Search STRING forward : / STRING.
    Search STRING backward: ? STRING.
  3. Repeat search: n
    Repeat search in opposite direction: N (SHIFT-n)
  4. Replace: Same as with sed, Replace OLD with NEW:
    First occurrence on current line: :s/OLD/NEW
    Globally (all) on current line: :s/OLD/NEW/g
    Between two lines #,#: :#,#s/OLD/NEW/g
    Every occurrence in file: :%s/OLD/NEW/g

References:

Tony Chen’s vi-manual
Felix Gers’s manual
vi reference on pages.de
RefCard on digilife.be (pdf)