0

I have files:

alpha_123_abc_file.txt
beta_456_def_file.txt
gamma_789_ghi_file.txt

Is there a way to rename all to cut the parts after the first _ character? To become:

123_abc_file.txt
456_def_file.txt
789_ghi_file.txt

I've looked into the perl tool but I an unsure if it has the capability to search out a pattern like that.

user1081491
  • 5
  • 1
  • 2
  • 1
    Given the input file names you posted, what should happen if `123_abc_file.txt` already exists when you try to rename `alpha_123_abc_file.txt`? – Ed Morton Aug 21 '20 at 23:38
  • @EdMorton I don't think a file conflict will be an issue. The files are in a temporary project directory so there are only a few at a time in it. – user1081491 Aug 21 '20 at 23:43
  • 1
    Perl is a general-purpose programming language, so yes, it has this capability. (I could say the same thing about "the Python tool", "the Java tool", "the C++ tool", etc.) Are you asking us to write a Perl program for you? – ruakh Aug 21 '20 at 23:43
  • 1
    @user1081491 it only takes 2. If you have `foo_123_abc_file.txt` and `bar_123_abc_file.txt` in that directory then the first rename will be OK but the 2nd one will try to overwrite the first. – Ed Morton Aug 21 '20 at 23:45
  • @ruakh I'm trying to figure it out myself but I'm having trouble finding the code to do a rename like that. All I've found says that perl will rename a keyphrase like the _ character, but I don't know how to make it only apply to the first _ character. – user1081491 Aug 22 '20 at 00:01
  • 1
    @user1081491: Re: "perl will rename a keyphrase like the _ character": Do you have a link to what you're referring to? Because as I said, Perl is a general-purpose programming language. It can rename anything to anything, using whatever arbitrary logic you might want to use to set the filenames. This isn't a "find the code" situation, it's a "write the code" situation. – ruakh Aug 22 '20 at 00:09
  • $ rename '\_(.*)' *.txt – Arundeep Chohan Aug 22 '20 at 00:23

1 Answers1

2
for file in *_*; do echo mv -- "$file" "${file#*_}"; done

Remove the echo when you're done testing and ready to actually do the mv.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185