parse output
:newbie: Ok I have a newbie Q.. I script heavily in the Windows World (I know I'm a trader but, I'm starting to love the power of the dark-side) and trying to learn bash scripting. What I'm trying to do is create a script that will read the output from ls and set a variable for each element it returns. I am looking more so for the extension of the file that is returned. For example in the windows world it would be
for /f "tokens=2 delims=." %%i in ('dir c:\home\fred.* /b') do set ext=%%i The main thing I'm looking for is in Linux, read the contents of a directory for a file that starts with a certain name. Then sets the extension of that file as a variable so it can be used later on in the script. This is what I have so far. ===================================== #!/bin/sh if test -z $2 ; then echo Need input echo $0 vm_to_move target_server exit $? fi ls -al /home/vmware/vmware/$1/$1.vmx |grep -i "vmx" >/dev/null #this is where I would use the windows command from above if [ $? = 0 ] then ext=vmx elif [ $? = 1 ] then ext=cfg fi #makes dir on remote host echo making /home/vmware/vmware/$1 on $2 ssh vmware@$2 mkdir /home/vmware/vmware/$1 #copying home files echo copying config files from /home/vmware/vmware/$1 to $2 scp /home/vmware/vmware/$1/* vmware@$2:/home/vmware/vmware/$1 #register vm on new host echo registering $1 on $2 ssh vmware@$2 vmware-cmd -s register /home/vmware/vmware/$1/$1.$ext #copying image file echo copying /vmfs/vol1/$1 to $2:/vmfs/vol1 scp /vmfs/vol1/$1* vmware@$2:/vmfs/vol1 ============================================== I am looking for a way to read the extension instead of having it hard coded. Any and all help with this would be greatly appreciated! THANKS!!!!!! |
Hi, and welcome to LQ!
What does %%i do in the windows script? I can't fully understand what exactly you're after ... But if you want to do a grep and be able to use the bit after the period you may want to have a closer look at sed or awk... Cheers, Tink |
Try 'echo $filename | rev | cut -d . -f 1 | rev'
rev reverses whatever it's given and cut will search up to the first . and return everything before that. |
Whenever you use for in a bath file you have to use 2 %% before the variable.
Excerpt: (from for /?) To use the FOR command in a batch program, specify %%variable instead of %variable. |
Quote:
|
variable_name=`echo $filename | rev | cut -d . -f 1 | rev`
Notice before echo and after rev are `(backtick) not '(single quote). Very important. Backticks tell the shell to execute the command before assignment. ` can be found right next to '1' on the keyboard. |
Sweet!!! Thank you very much sir!
|
You're welcome. :)
|
All times are GMT -5. The time now is 04:01 PM. |