0

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 )

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for answer , i tried it but for some reason the read prompt is not working
Right, I have to move the parameter expansion just after the do, try it now.
I think something still is a miss , the read prompt never comes. Check this out del.dog/raw/crirezutus
Yep, another fd for the first read should fix the issue.
Thanks , the solution at the bottom works flawlessly. The one at top still doesn't work for some reason . I am marking it as accepted answer . ( You might possibly want to edit / remove the top one )
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.