Remove part of file name using for loop in terminal
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.
Related videos on Youtube
ashik992
Updated on September 18, 2022Comments
-
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 over 10 yearsCould you explain what does each part of the command?
-
Agoston Horvath over 10 yearsIt'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 over 10 yearsA 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 over 10 yearsOk, could you add that to the actual answer?