Bash script to remove 'x' amount of characters the end of multiple filenames in a directory?

前端 未结 3 1873
我在风中等你
我在风中等你 2020-12-03 19:07

I have a list of file names in a directory (/path/to/local). I would like to remove a certain number of characters from all of those filenames.

相关标签:
3条回答
  • 2020-12-03 19:46

    This sed command will work for all the examples you gave.

    sed -e 's/\(.*\)_.*\.moc1/\1_.moc1/'
    

    However, if you just want to specifically "remove 5 characters before the last extension in a filename" this command is what you want:

    sed -e 's/\(.*\)[0-9a-zA-Z]\{5\}\.\([^.]*\)/\1.\2/'
    

    You can implement this in your script like so:

    for filename in /path/to/local/*.moc1; do
    
        mv $filename "$(echo $filename | sed -e 's/\(.*\)[0-9a-zA-Z]\{5\}\.\([^.]*\)/\1.\2/')";
    
    done
    

    First Command Explanation

    The first sed command works by grabbing all characters until the first underscore: \(.*\)_

    Then it discards all characters until it finds .moc1: .*\.moc1

    Then it replaces the text that it found with everything it grabbed at first inside the parenthesis: /\1

    And finally adds the .moc1 extension back on the end and ends the regex: .moc1/

    Second Command Explanation

    The second sed command works by grabbing all characters at first: \(.*\)

    And then it is forced to stop grabbing characters so it can discard five characters, or more specifically, five characters that lie in the ranges 0-9, a-z, and A-Z: [0-9a-zA-Z]\{5\}

    Then comes the dot '.' character to mark the last extension : \.

    And then it looks for all non-dot characters. This ensures that we are grabbing the last extension: \([^.]*\)

    Finally, it replaces all that text with the first and second capture groups, separated by the . character, and ends the regex: /\1.\2/

    0 讨论(0)
  • 2020-12-03 19:55
     mv $filname $(echo $filename | sed -e 's/.....\.moc1$//');
    

    or

     echo ${filename%%?????.moc1}.moc1
    

    %% is a bash internal operator...

    0 讨论(0)
  • 2020-12-03 19:56

    This might work for you (GNU sed):

    sed -r 's/(.*).{5}\./\1./' file
    
    0 讨论(0)
提交回复
热议问题