Extract directory from path [duplicate] - string

This question already has answers here:
Getting the parent of a directory in Bash
(13 answers)
Closed 1 year ago.
In my script I need the directory of the file I am working with. For example, the file="stuff/backup/file.zip". I need a way to get the string "stuff/backup/" from the variable $file.

dirname $file
is what you are looking for

dirname $file
will output
stuff/backup
which is the opposite of basename:
basename $file
would output
file.zip

Using ${file%/*} like suggested by Urvin/LuFFy is technically better since you won't rely on an external command. To get the basename in the same way you could do ${file##*/}. It's unnecessary to use an external command unless you need to.
file="/stuff/backup/file.zip"
filename=${1##*/} # file.zip
directory=${1%/*} # /stuff/backup
It would also be fully POSIX compliant this way. Hope it helps! :-)

For getting directorypath from the filepath:
file="stuff/backup/file.zip"
dirPath=${file%/*}/
echo ${dirPath}

Simply use $ dirname /home/~username/stuff/backup/file.zip
It will return /home/~username/stuff/backup/

Related

rename file using a loop [duplicate]

This question already has answers here:
Rename multiple files based on pattern in Unix
(24 answers)
Closed 2 years ago.
I have a lot of file with the same format (???_ideal.sdf) name and I need to rename all (???.sdf) removing form the name "ideal". For example:
Files:
002_ideal.sdf
ERT_ideal.sdf
234_ideal.sdf
sCX_idel.sdf
New Files:
002.sdf
ERT.sdf
234.sdf
SCX.sdf
I thought to using a loop but I don’t know how to indicate that in the new file name should be removed "individual".
For example:
for file in ???_individual.sdf; mv $file what?
With your shown samples, could you please try following. This will only print the rename command on terminal(for safer side, check and make sure if commands are fine and looking ok to you first before actually renaming files), to perform actual rename remove echo from following.
for file in *_ideal.sdf
do
echo mv "$file" "${file/_ideal/}"
done
Based on this answer you can also write it as one line with:
rename 's/^(.*)_ideal.png/$1.png/s' **/**
First parameter replaces the the _ideal.png, second one means all files.

Bash script file as input [duplicate]

This question already has answers here:
Command not found error in Bash variable assignment
(5 answers)
Closed 2 years ago.
i am trying to give an file as input to me my shell script:
#!/bin/bash
file ="$1"
externalprogram "$file"
echo 'unixcommand file '
i am trying to give the path to my file but it says always
cannot open `=/home/username/documents/file' (No such file or directory)
my path is this /home/username/Documents/file
i do this in terminal : ./myscript.sh /home/username/Documents/file
can someone help me please?
When you say
file ="$1"
with a space after "file", you're running something called file with =$1 as an argument. There probably actually is a utility called file. If you want to assign $1 to a variable called file, you don't need the space:
file="$1"
there shouldn't be a space before = in the second line.
file=$1 should be good enough.
Check what shellcheck says about your code:
^-- SC1068: Don't put spaces around the = in assignments (or
quote to make it literal).
You can read more about SC1068 case on its Github
page.
#!/bin/bash
file=$1
code $file
echo "aberto o arquivo ${file} no vscode"
I made this code snippet to demonstrate, I pass a path and it opens the file in vscode

Using for in a Script, Ubuntu command line

How can I pass each one of my repository files and to do something with them?
For instance, I want to make a script:
#!/bin/bash
cd /myself
#for-loop that will select one by one all the files in /myself
#for each X file I will do this:
tar -cvfz X.tar.gz /myself2
So a for loop in bash is similar to python's model (or maybe the other way around?).
The model goes "for instance in list":
for some_instance in "${MY_ARRAY[#]}"; do
echo "doing something with $some_instance"
done
To get a list of files in a directory, the quick and dirty way is to parse the output of ls and slurp it into an array, a-la array=($(ls))
To quick explain what's going on here to the best of my knowledge, assigning a variable to a space-delimited string surrounded with parens splits the string and turns it into a list.
Downside of parsing ls is that it doesn't take into account files with spaces in their names. For that, I'll leave you with a link to turning a directory's contents into an array, the same place I lovingly :) ripped off the original array=($(ls -d */)) command.
you can use while loop, as it will take care of whole lines that include spaces as well:
#!/bin/bash
cd /myself
ls|while read f
do
tar -cvfz "$f.tar.gz" "$f"
done
you can try this way also.
for i in $(ls /myself/*)
do
tar -cvfz $f.tar.gz /myfile2
done

Extracting the file name from a full path string [duplicate]

This question already has answers here:
Get just the filename from a path in a Bash script [duplicate]
(6 answers)
Closed 4 years ago.
Let's say I have a string which represents the full path of a file:
full_path='./aa/bb/cc/tt.txt'.
How can I extract only the file name tt.txt?
Please don't tell me to use echo $full_path | cut -d'/' -f 5.
Because the file may be located in a deeper or shallower folder.
The number, 5, cannot be applied in all cases.
if you are comfortable with python then, you can use the following piece of code.
full_path = "path to your file name"
filename = full_path.split('/')[-1]
print(filename)
Use the parameter expansion functionality.
full_path='./aa/bb/cc/tt.txt'
echo ${full_path%/*}
That will give you the output
./aa/bb/cc
And will work any number of directory levels deep, as it will give you everything up to the final "/".
Edit: Parameter expansion is very useful, so here's a quick link for you that gives a good overview of what is possible: http://wiki.bash-hackers.org/syntax/pe
You can use this construct
echo "$full_path" | sed 's/\/.*\///'

Linux Bash Scripting: Declare var name from user or file input

Hi i would like to do the following.
./script.sh some.file.name.dat another.file.dat
Filename1=$(echo "$1"|cut -d '.' -f 1,2)
Filename2=$(echo "$2"|cut -d '.' -f 1,2)
tempfile_"$1"=$(mktemp)
tempfile_"$2"=$(mktemp)
I know this code isn't working. I need to create these temporary files and use them in a for loop later, in which i will do something with the input files and save the output in these temporary files for later usage. So basically i would like to create the variable names dependent on the name of my input files.
I googled a lot and didn't found any answers to my problem.
I would like to thank for your suggestions
I'll suggest an alternate solution to use instead of entering the variable naming hell you're proposing (Using the variables later will cause you the same problems later, the scale will just be magnified).
Use Associative arrays (like tempfile[$filename]) instead of tempfile_"$filename". That's what associative arrays are for:
declare -A tempfile
tempfile[$1]=$(mktemp)
tempfile[$2]=$(mktemp)
cat ${tempfile[$1]}
cat ${tempfile[$2]}
rm -f ${tempfile[$1]}
rm -f ${tempfile[$2]}
Note: Associative arrays require bash version 4.0.0 or newer.
If you dont have Bash version 4.0.0 or newer, see the following answers for great workarounds that dont use eval.
How to define hash tables in Bash?
Associative arrays in Shell scripts
You cannot do that since Bash just doesn't allow dots in the names of identifiers/variables. Both of your arguments $1 and $2 have dots (periods) in them and that cannot be used in variable names you're trying to create i.e. tempfile_$1
See this page for details.
Try this:
eval "tempfile_"$1"=$(mktemp)"
eval "tempfile_"$2"=$(mktemp)"
Use something like:
f1=`echo $1|tr '.' '_'`
declare "tempfile_$f1=$(mktemp)"
Check out How to define hash tables in bash?

Resources