Issue
for example:
file-name-has-this-length.nfo
into,
assign var1=file
assign var2=name
assign var3=has
assign var4=this
assign var5=lenght
assign ext=.nfo # ext with or
# without period
taking any delimiters -
_
.
out!
My initial idea (but not limited to) is to create separated directories based on the name of the file. And any future scripts to use those names as a reference.
EDIT: I didn't find anything about "separate strings from file [names] to store their respective values". If you think this question should be moved to some other place just do it, but I need this problem solved.
This is not a duplicated!
Solution
IFS
, read
and <<<
are all bash elements that are explained in bash tutorials.
IFS='-_.' read -r -a parts <<< "file-name-has-this-length.nfo"
This splits the filename in an array, where each element is one string from the filename. The split is done on the characters defined in the IFS variable. You can read on IFS in The Meaning of IFS in Bash Scripting (among others that you can search for). Using the IFS to split strings is a common method in bash.
So:
parts[0] ==> file
parts[1] ==> name
parts[2] ==> has
parts[3] ==> this
parts[4] ==> length
parts[5] ==> nfo
This solution does not make any assumptions as to the number of words in the filename. An array can contain any number of elements, so this is the best - general - solution. And you can assume that the last item in the array (highest index) is the extension.
With an array, you can loop through the items to create directories. See You don't know Bash: An introduction to Bash arrays for many hints on how to use arrays.
If you can assume that the filename will always have the same number of elements, you can do:
#!/bin/bash
IFS='-_.' read -r -a parts <<< "file-name-has-this-length.nfo"
var1="${parts[0]}"
var2="${parts[1]}"
var3="${parts[2]}"
var4="${parts[3]}"
var5="${parts[4]}"
ext="${parts[5]}"
echo "$var1"
echo "$var2"
echo "$var3"
echo "$var4"
echo "$var5"
echo "$ext"
About your questions:
1. Are they builtin specifically for Bash or Linux API?
This is all pure bash, and there isn't any trickery here.
2. How can I change the name of the variables?
Look at the code above. var1, var2, ... can be changed to anything you want.
3. Is this the practical way of doing things or just a trick?
This is the practical way of doing it. Bash is flexible; if it does what you require, it is ok. Once you have read through a bash tutorial, you can read more advanced concepts in this FAQ: BASH Frequently Asked Questions
Answered By - Nic3500 Answer Checked By - Robin (WPSolving Admin)