0

I have created a script in /home/prashast directory. I've created another directory inside /home/prashast named TestDirectory. I've multiple files inside /home/prashast/TestDirectory. While running a script from /home/prashast directory its not effecting the files in /home/prashast/TestDirectory.

#!/bin/bash
for f in $(ls /home/prashast/TestDirectory/); do
     mv "$f.txt" "$f.text";
done
αғsнιη
  • 40,939
  • 15
  • 71
  • 114
Prashast
  • 51
  • 1
  • 6
  • When i am writing echo $f i am able to see all the files in the directory but i could not rename the files inside the directory. and getting the error "mv: cannot stat ‘file1.txt.txt’: No such file or directory" – Prashast Aug 13 '17 at 07:25

1 Answers1

6

Don't parse ls result, use this code instead.

for f in /home/prashast/TestDirectory/*; do
    echo mv "$f" "${f%.*}.text";
done

The ${f%.*} that we used is a shell parameter expansion expression (cut-up-to-first-suffix); stripping start from end to the begging of filename till first . seen.

Read chapter on Bash shell parameter expansion for more.

αғsнιη
  • 40,939
  • 15
  • 71
  • 114
  • Could you please explain ${f%%.*} – Prashast Aug 13 '17 at 08:05
  • Is there any benefit to quoting the path in this? Like: `for f in "/home/prashast/TestDirectory/*"` I always want to do it thinking it's going to help with special characters in the filenames but I don't see many people do that so I'm guessing there is no real benefit to it? – jesse_b Aug 13 '17 at 13:15
  • for me is difficult to answer your this question, but basically as my experience mostly `for loop` is using for one level of path and only including files to process, so `*` can do the job for any matching file and if it's two or more levels can be `/*/*` in path and inside `for... ` can decide the other processes. – αғsнιη Aug 13 '17 at 13:36