Remove part of file name using for loop in terminal

8,392

Solution 1

for i in *.txt; do mv $i ${i%%.txt}; done

It's a simple for cycle, just like the one you wrote. Note I've used ; instead of newlines so that I can type it into a single line. The only construct that is new to you is the ${i%%.txt}, which simply means $i, with whatever following the %% signs cut off from the end of $i.

A good tip: if unsure what would happen, try adding echo in front of the actual command, so that you would see the exact commands that are to be executed. E.g.:

for i in *.txt; do echo mv $i ${i%%.txt}; done 

Solution 2

As this web says... you can try bash String Manipulations

You can use two different "operators" inside the parameters (curly braces) ,Those are the # and the % operators for trimming patterns off the beginning or end of a string.

Your case could be:

${variable%pattern} Trim the shortest match from the end

In the Terminal would be:

for i in *.old
do 
mv $i ${i%\.*}
done

Here you have examples:

Given:

foo=/tmp/my.dir/filename.tar.gz

We can use these expressions:

path = ${foo%/*}

To get: /tmp/my.dir (like dirname)

file = ${foo##*/}

To get: filename.tar.gz (like basename)

base = ${file%%.*}

To get: filename

ext = ${file#*.}

To get: tar.gz


${variable%pattern}

Trim the shortest match from the end

${variable##pattern}

Trim the longest match from the beginning

${variable%%pattern}

Trim the longest match from the end

${variable#pattern}

Trim the shortest match from the beginning

Hope it helps.

Share:
8,392

Related videos on Youtube

ashik992
Author by

ashik992

Updated on September 18, 2022

Comments

  • ashik992
    ashik992 over 1 year

    In terminal using for loop we can add a part before or after the file name. But if we want to remove it how do we do this? For example we can add .old after all .txt files name using the command bellow

    $for i in *.txt
    >do
    >    mv $i $i.old
    >    done
    

    But my question is how do we remove this .old just using the same technique?

  • Braiam
    Braiam over 10 years
    Could you explain what does each part of the command?
  • Agoston Horvath
    Agoston Horvath over 10 years
    It's a simple for cycle, just like the one you wrote. Note I've used ; instead of newlines so that I can type it into a single line. The only construct that is new to you is the ${i%%.txt}, which simply matches $i, with whatever following the %% signs cut off from the end of $i.
  • Agoston Horvath
    Agoston Horvath over 10 years
    A good tip: if unsure what would happen, try adding echo in front of the actual command, so that you would see the exact commands that are to be executed. E.g., for i in *.txt; do echo mv $i ${i%%.txt}; done
  • Braiam
    Braiam over 10 years
    Ok, could you add that to the actual answer?