2

My file structure now is:

  • Input
    • 1
      • pre.nii
    • 2
      • pre.nii

I would like it to be:

  • Input
    • 1_pre.nii
    • 2_pre.nii

From the Input folder, I tried: for i in */pre.nii; do echo $i_pre.nii; done

But that gave me:

    .nii
    .nii

I also tried: for i in */pre.nii; do echo ${i%/*}; done that gave me:

    1
    2

But I couldn't figure out how to use the % string operator and add the correct suffix.

  • 2
    underscore is a valid part of a bash variable; try ${i}_pre.nii ... – Jeff Schaller Jan 12 '16 at 19:26
  • @JeffSchaller That also worked: for i in */pre.nii; do echo mv ${i} ${i%/*}_pre.nii; done. So, for the suffix to be added after a string operator, it should be outside the curly brackets. Is that correct? – Brent Womble Jan 12 '16 at 21:25
  • 2
    yes; the parameter expansion is delineated by the braces ${...} – Jeff Schaller Jan 12 '16 at 21:37
4

To replace one / (escaped with \) by _:

for i in */pre.nii; do echo mv "$i" "${i/\//_}"; done

If everything looks fine, remove echo.

  • 2
    Thank you! To make sure I understand: You used the string operator "${i/old/new}" but to use / as old you had to escape it with \ – Brent Womble Jan 12 '16 at 20:00
  • 2
    That is correct. – Cyrus Jan 12 '16 at 20:12
1

I tend to use sed to do the replacement and test before making changes:

for i in */pre.nii;
do 
   j=$(echo $i | sed 's/\//_/')
   echo $j
done

then run it

for i in */pre.nii;
do 
   j=$(echo $i | sed 's/\//_/')
   mv -v $i $j
done
  • Maybe this will be easier to read: sed 's|/|_|' instead of the backspaced sed 's/\//_/' – user79743 Jan 13 '16 at 3:27

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.