Renaming files in a UNIX directory - shell scripts

I am trying to write a script that will take the current working directory, scan each file and check if it is a .txt file. Then take each file (this is a text file) and check to see if it contains an underscore anywhere in its name, and if it changes the underscore to a hyphen.

I know this is a high order, but here is the rough code that I still have:

#!/bin/bash
count=1
while((count <= $#))
       do
          case $count in
               "*.txt") sed 's/_/-' $count
          esac
          ((count++))
done

What I thought was that this would cause the files in the current working directory to be used as arguments and check each file (represented by $ count or the file in "count"). Then, for each file, it will check to see if that .txt has ended, and if that happened, it would change each underscore to a hyphen using sed. I think that one of the main problems that I am facing is that the script does not read files from the current working directory. I tried to include the directory after the command to run the script, but I think that each line was taken instead of each file (since there are 4 or so in each line).

In any case, any help would be greatly appreciated! Also, I'm sorry that my code is so bad, I'm very new to UNIX.

+5
4
for fname in ./*_*.txt; do
  new_fname=$(printf '%s' "$fname" | sed 's,_,-,')
  mv "$fname" "$new_fname"
done
+2

:

rename 's/_/-/' *.txt
+1
$ ls * .txt | while read -r file; do echo $ file |
  grep> / dev / null _ && mv $ file $ (echo $ file | tr _ -); done

(unverified)

0
source

Thank you all for participating! Overall, I think the solution I found was most suitable for my skill level:

ls *.txt | while read -r file; do echo file |
   mv $file $(echo $file | sed 's,_,-,');
done

This got what I needed, and for my purposes I am not too worried about spaces. But thanks for all your wonderful suggestions, you are all very smart!

0
source

All Articles