Search code examples
bashloopsfilerenameparameter-expansion

i want to change the names of the files and this change is in the middle. i basically need to remove a part of the variable and write something else


i have tried this

$ls 
casts.c endian.c ptr.c signed-unsigned-representations.c signed-unsigned.c test-hard-link.c

$for i in *.c;do mv "$i" "$i"__swa.c; done

$ls
casts.c__swa.c endian.c__swa.c ptr.c__swa.c signed-unsigned-representations.c__swa.c signed-unsigned.c__swa.c test-hard-link.c__swa.c

and i know that because my i variable is *.c so when i try to rename and add the (__swa.c) part it just gets added on the variable name.

i need the files to be renamed like this:

casts__swa.c  endian__swa.c  ptr__swa.c  signed-unsigned-representations__swa.c                signed-unsigned__swa.c  test-hard-link__swa.c

Solution

  • Using Bash's parameter expansion , you could do something like this:

    for f in *.c; do
        echo mv "$f" "${f%%.c}"__swa.c
    done
    

    (Remove the echo of course, if it looks like it will do what you want)

    But I generally rather use the more flexible rename using Perl, as suggested in the answer by Cyrus.