0

I have some numeric files like:

test01-aaa.txt
test02-bbb.txt
test03-ccc.txt
test04-ddd.txt

I need to remove aaa,bbb,ccc,ddd part from the name. what is the best way i can do? I tried with 'rename' command, but how can i use this way?

rename -v "test??-*.txt" "test??.txt" *.txt

to have files like this:

test01.txt
test02.txt
test03.txt
test04.txt

1 Answers1

1

A simple loop in the shell (which avoids the fact that there are several conflicting variants of the rename utility):

for name in test??-*.txt; do
    mv "$name" "${name%%-*}.txt"
done

The loop iterates over all names in the current directory matching the given pattern. For each such name, the end of the string is trimmed from the first - using a standard parameter substitution. The substitution ${variable%%pattern} removes the longest suffix string matching pattern from the value of the variable variable. We then add the .txt suffix back onto the result of the substitution.

In the bash shell, you may want to set the nullglob shell option before running the loop, so that it does not run a single iteration if there is no matching filename.

With mv on a GNU system (or any system with mv from GNU coreutils), you may use -b or --backup to back up the destination file if it happens to already exist. Without -b, the above loop would handle name conflicts by simply overwriting the existing file.

Kusalananda
  • 333,661
  • Thank you so much. it works. is it possible to use 'patterns' (test??-.txt) in rename command? something like this: rename "test??-.txt" "test??.txt" *.txt Is it possible? – Sepehr roosta Jan 12 '22 at 20:47
  • 1
    @Sepehrroosta The Perl-based rename command takes a Perl expression, for example a substitution command (s/regular-expression/replacement/), not shell globbing patterns. With it, you could use s/-.*/.txt/ as the expression. Since I don't know what replace you are using, I opted for not mentioning that command at all and instead use a loop that is guaranteed to work the same regardless of shell and Linux distribution. – Kusalananda Jan 12 '22 at 21:28