Sachin
Sachin

Reputation: 1309

How to rename all files one by one through find command?

I want to append a string to each file printed by the find command . It prints each file on a new line. The thing is that each file has a unique string to be appened to its name. This is how i need it to work

Run the find command Print the first result Have a read prompt for user to enter string , then append that string to the name. Print the second result. Have a read prompt .. then append that string to the second name ... and so on for all of the files

I have tried using while loop to do this , although haven't been successful yet

find . -type f -name 'file*' | 
  while IFS= read file_name; do 
    read -e -p "Enter your input : " string
    mv "$file_name" "$file_name $string" 
  done

For example. Lets say the original filename is demo1.mp4 , and i enter 'test' in the read prompt , then the filename should be renamed to 'demo1 test.mp4' ( There should be a space before appending the string to the end of filename )

Upvotes: 0

Views: 107

Answers (1)

Jetchisel
Jetchisel

Reputation: 7831

You can do string slicing via Parameter Expansion, something like.

find . -type f -name 'file*' | {
  while IFS= read file_name; do
    name="${file_name%.*}"
    ext="${file_name#*"$name"}"
    read -e -p "Enter your input : " string </dev/tty
    echo mv "$file_name"  "$name $string$ext" 
  done
}

Since there are two reads inside the while loop, reading from </dev/tty is another work around, not sure if it is an O.S. specific or not but if it is available /dev/tty then it should fix the issue.


There are two read inside the while loop another approach is to use Process Substitution, besides using /dev/tty

 while IFS= read -u9 file_name; do
    name="${file_name%.*}"
    ext="${file_name#*"$name"}"
    read -e -p "Enter your input : " string
    echo mv "$file_name"  "$name $string$ext" 
  done 9< <(find . -type f -name 'file*')

Remove the echo if you're satisfied with the output.

Some good examples are here Howto Parameter Expansion

Some good example of Process Substitution.

Upvotes: 1

Related Questions