In my bash script I need to extract just the path from the given URL. For example, from the variable containing string:
http://login:[email protected]/one/more/dir/file.exe?a=sth&b=sth
I want to extract to some other variable only the:
/one/more/dir/file.exe
part. Of course login, password, filename and parameters are optional.
Since I am new to sed and awk I ask you for help. Please, advice me how to do it. Thank you!
The filename is the last part of the URL from the last trailing slash. For example, if the URL is http://www.example.com/dir/file.html then file. html is the file name.
In this case, first, we need the current script's path, and from it, we use dirname to get the directory path of the script file. Once we have that, we cd into the folder and print the working directory. To get the full or absolute path, we attach the basename of the script file to the directory path or $DIR_PATH.
In Linux, the basename command prints the last element of a file path. This is especially useful in bash scripts where the file name needs to be extracted from a long file line. The “basename” takes a filename and prints the filename's last portion. It can also delete any following suffix if needed.
There are built-in functions in bash to handle this, e.g., the string pattern-matching operators:
For example:
FILE=/home/user/src/prog.c echo ${FILE#/*/} # ==> user/src/prog.c echo ${FILE##/*/} # ==> prog.c echo ${FILE%/*} # ==> /home/user/src echo ${FILE%%/*} # ==> nil echo ${FILE%.c} # ==> /home/user/src/prog
All this from the excellent book: "A Practical Guide to Linux Commands, Editors, and Shell Programming by Mark G. Sobell (http://www.sobell.com/)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With