rehman rehman - 2 months ago 13
Bash Question

copy file to folder have same name with different extension in parent directory

my files are

1996-08-30T02.11.41.940_10

1997-03-04T17.24.17.650_17

1997-04-01T15.43.26.390_20


and folders are

1996-08-30T02.11.41.940_5.1

1997-03-04T17.24.17.650_5.0

1997-04-01T15.43.26.390_4.5


the files and folders are in same directories. I want to move file to a folder whose name is same with different extension
ex:
The file 1996-08-30T02.11.41.940_10 should be move in folder 1996-08-30T02.11.41.940_5.1

I Have tried this, but no use

for file in ./*T* ; do mv -v $file ${file%_*}; done

Answer Source

You were very close:

$ for file in ./* ; do [ -f "$file" ] && mv -v "$file" "${file%_*}"*/; done
'./1996-08-30T02.11.41.940_10' -> './1996-08-30T02.11.41.940_5.1/1996-08-30T02.11.41.940_10'
'./1997-03-04T17.24.17.650_17' -> './1997-03-04T17.24.17.650_5.0/1997-03-04T17.24.17.650_17'
'./1997-04-01T15.43.26.390_20' -> './1997-04-01T15.43.26.390_4.5/1997-04-01T15.43.26.390_20'

Notes:

  1. Unless you specifically want the shell to mangle things, always put shell variables in double quotes.

  2. We added test [ -f "$file" ] so that we only try to move regular files, not directories.

  3. The directory will match ${file%_*}"*/. We are assuming, as per the question discription, that there is only one such directory.