1

I have many files of the form {a}_{b}_R1.txt I would like to change the basenames of these files to {a}.{b}.txt how would I go about this? I can only find out how to do this with extensions. Thanks.

quantik
  • 776
  • 12
  • 26
  • Possible duplicate of [Rename multiple files by replacing a particular pattern in the filenames using a shell script](http://stackoverflow.com/questions/6840332/rename-multiple-files-by-replacing-a-particular-pattern-in-the-filenames-using-a) – JNevill Apr 19 '17 at 18:45
  • What did you try for yourself and fail? – Inian Apr 19 '17 at 18:47
  • I tried `mv *_R1.fasta *.fasta` did not remove the `_R1` after that it'd be easier to replace the single `_` – quantik Apr 19 '17 at 18:48
  • @JNevill solution doesnt work for me on Mac – quantik Apr 19 '17 at 18:49
  • @quantik: Can you give a couple of actual file names and their value to be replaced? – Inian Apr 19 '17 at 18:49
  • @Inian Sure. `K_SPF_R1.txt Muc0582_SPF_R1.txt Muc0583_SPF_R1.txt` – quantik Apr 19 '17 at 18:50
  • I figure doing two successive for loops may work: `for f in *.txt; do mv "$f" "`echo $f | sed s/_R1//`"; done` then for f in *.txt; do mv "$f" "`echo $f | sed s/_/./`"; done – quantik Apr 19 '17 at 18:54

2 Answers2

3

You can just a simple loop in the native bash shell under OS X from terminal, after navigating to the folder containing those text files,

# Looping for all the text files in the current 
# directory
for file in *.txt; do
    # Stripping off '_R1' from the file-name
    temp1="${file//_R1/}"
    # Replacing '_' with '.' and renaming the file to the name generated
    temp2="${temp1//_/.}"
    echo "$temp2" "$file"
    #mv -v "$file" "$temp2"
done

Remove the line with echo and uncomment the mv once you find the names are changed accordingly.

for file in *.txt; do temp1="${file//_R1/}"; temp2="${temp1//_/.}"; mv -v "$file" "$temp2"; done
Inian
  • 80,270
  • 14
  • 142
  • 161
2

This works as well:

for f in *.txt; do mv "$f" "echo $f | sed s/_R1//"; done then for f in *.txt; do mv "$f" "echo $f | sed s/_/./";

quantik
  • 776
  • 12
  • 26
  • 2
    You don't need `sed` or any third party tools for this, can be done with the native `bash` features alone – Inian Apr 19 '17 at 19:00