Search code examples
bashfilenamesparentheses

Parenthesis in a file name -- batch conversion


I have a bunch of files that contain parenthesis, like

long_file_name (12).txt 

(note the space before the number) I would like to extract all the numbers from the file names. How can I do that? I have found this thread stackoverflow link but it didn't help -- the problem is that I want to assign filename to a variable and not change each of the files separately.

Thanks for all help


Solution

  • You can do this in bash by using the variable interpolation/substitution:

    $ F="long_file_name (12).txt"
    $ echo ${F/*(/}
    12).txt
    $ G=${F/*(/}; echo ${G/)*/}
    12
    $ G=${F/*(/}; H=${G/)*/}; echo $H
    12
    $
    

    In short, this will give you just the number in parentheses from a filename:

    F="long_file_name (12).txt"
    G=${F/*(/}; H=${G/)*/}; echo $H
    

    If you have filenames in other formats, please supply more examples to test with.