LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   I cannot figure out how to get user input into a script (https://www.linuxquestions.org/questions/linux-newbie-8/i-cannot-figure-out-how-to-get-user-input-into-a-script-767130/)

froster 11-05-2009 02:09 PM

I cannot figure out how to get user input into a script
 
I have a section of a script that is supposed to change the filename of similar files in a directory. It works the way I need it to work, except that I would like to input the new filename each time it runs without having to edit the script.

I capture 5-6 images into ~/screenshots. They are labeled Picture 1.png, Picture 2.png, etc. I would like to be able to rename them as Lesson 1.png, Lesson 2.png, and so forth. It works if I hardcode the new NAME (Lesson) into the script, but I want to replace NAME with a variable that I can input at a prompt or pass into the script from another. I have tried setting a variable and replacing "Lesson" with $variable in line #11, but that leaves me with only the extension and no filename. I have also tried using $1 on the command line:

ie: $ ./namer $1
and fname=$1
and replace Lesson with $fname in line #11
but it still changes everything to a null filename

Here is what I have that works:

1 #!/bin/sh
2 # I need to get user input for new filename
3
4 # cd to screenshots directory
5 cd ~/screenshots
6
7 # this next line removes spaces from filenames
8 for f in *; do mv "$f" `echo $f | tr ' ' '_'`; done
9
10 #this changes the Picture to Lesson
11 ls * | awk '{print("mv -v "$1" "$1)}' | sed 's/Picture/Lesson/2' | /bin/sh


How do I get a variable into this script?

Thanks in advance!

JF

Disillusionist 11-05-2009 02:13 PM

Code:

read -p "Please enter new filename: " new_file
You will need to change the sed part of the script:
Code:

ls * | awk '{print("mv -v "$1" "$1)}' | sed "s/Picture/$new_file/2" | /bin/sh
You should be able to use $1, but you need to replace the single quotes in the sed statement into double quotes.

froster 11-05-2009 07:13 PM

Thank you, Disillusionist! The double-quote was the fix I needed. Have a great day!

jf


All times are GMT -5. The time now is 08:31 PM.