0

An extension to the previous question that I asked: Rename an alphanumeric file

I have a directory that has subdirectories with an extension of *_upstream:

DHX30_vs_Control18.txt_events_without_u2af1_srsf2_altexons_upstream
GEMIN5_vs_Control19.txt_events_without_u2af1_srsf2_altexons_upstream

I want to rename them by removing everything after first '_' such that it becomes something like

DHX30
GEMIN5
3
for dir in ./*_*_upstream/
do 
  mv -- "$dir" "${dir%%_*}"
done

The above loop picks up every directory (the trailing slash does this) in the current directory that matches the pattern: "(something) underscore (something) underscore upstream". It then renames those directories by using parameter expansion to remove the longest match of: "underscore (anything)", which removes everything from-and-after the first underscore.

For example:

Setup:

mkdir DHX30_foo_upstream
mkdir GEMIN5_vs_Cblah_upstream
touch DX31_foo_upstream

Result:

$ tree
.
├── DHX30
├── DX31_foo_upstream
└── GEMIN5

2 directories, 1 file
2

If on Linux:

rename -v 's/_.*//' *_upstream/
  • You are correct, added slash. – ctrl-d Jun 29 '18 at 20:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.