Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract filename and path from URL in bash script

Tags:

bash

url

parsing

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!

like image 260
Arek Avatar asked Jul 29 '09 11:07

Arek


People also ask

How do I get the filename from a URL?

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.

How do I find the path of a file in bash?

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.

What is basename in bash script?

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.


1 Answers

There are built-in functions in bash to handle this, e.g., the string pattern-matching operators:

  1. '#' remove minimal matching prefixes
  2. '##' remove maximal matching prefixes
  3. '%' remove minimal matching suffixes
  4. '%%' remove maximal matching suffixes

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/)

like image 62
JESii Avatar answered Oct 03 '22 07:10

JESii