0

I have a text file that contains following

https://git.centos.org/git/rpms/abc.git
https://git.centos.org/git/rpms/abc.git/
https://git.centos.org/git/rpms/abc

When I run the following command,

reponame=$(echo $url | awk -F/ '{print $NF}' | sed -e 's/.git\/$//' | sed -e 's/.git//')
echo $reponame

I am supposed to get

abc

It fails for the lines ending in .git/ but it works for the other 2 cases.

  • You want abc from all three lines? – heemayl Mar 31 '16 at 10:36
  • Yes, I need it from all the 3 kind of lines. – sudhansh_ Mar 31 '16 at 10:37
  • Will the part to be extracted always located in the 5th /-separated field? I.e., will the string to parse always be something like 1://2/3/4/xxx.git or could it also be something like 1://2/3/4/5/xxx.git or 1://2/3/xxx.git? – kos Mar 31 '16 at 10:48
2

Using grep with PCRE (-P):

grep -Po '.*/\K[^.]+' file.txt

The desired portion is extracted by [^.]+, .*/ matches the portion before abc and \K discards the match.

Example:

$ cat file.txt 
https://git.centos.org/git/rpms/abc.git
https://git.centos.org/git/rpms/abc.git/
https://git.centos.org/git/rpms/abc

$ grep -Po '.*/\K[^.]+' file.txt
abc
abc
abc

Similar logic using sed, using pattern grouping:

$ sed -r 's#.*/([^.]+).*#\1#' file.txt 
abc
abc
abc
1

I know the question asks for a sed solution, however assuming the string to extract is always going to be in the 6th field like in the example this is more easily done using AWK:

awk -F/ 'match($6, /^[^.]+/, x) {print x[0]}' file
  • -F/: sets the input field separator to /;
  • match($6, /^[^.]+/, x): if the sixth field matches ^[^.]+ one or more times, stores the matches into an array x an executes the following block;
  • {print x[0]}: prints the first element of x.
% cat file
https://git.centos.org/git/rpms/abc.git
https://git.centos.org/git/rpms/abc.git/
https://git.centos.org/git/rpms/abc
% awk -F/ 'match($6, /^[^.]+/, x) {print x[0]}' file
abc
abc
abc

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.