3

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.

2
  • What's the desired output for above mentioned 3 lines ? – SHW Mar 31 '16 at 10:39
  • abc for each case – sudhansh_ Mar 31 '16 at 10:40
3

You have to remove the trailing slash before you print the last field with awk. Otherwise the last field will be empty.

Use

echo "$url" | sed -e 's#/$##' -e 's/\.git$//' | awk -F / '{print $NF}'

or even

echo "$url" | sed -e 's#/$##' -e 's/\.git$//' -e 's#^.*/##'

Tips:

  • You can give several sed commands to one invocation of sed so it is sometimes not necessary to pipe from sed to sed. Either sed -e 'cmd1' -e 'cmd2' ... or sed 'cmd1;cmd2;...' will work.
  • You can use a different delimiter for the s command of sed so you do not have to escape slashes in the pattern (I used # as a delimiter).
1
  • I tried the first one and it worked. Thank you. – sudhansh_ Mar 31 '16 at 10:49
1

Assuming all your lines in a file either have .git extension

ALSO SOLUTION IS GIVEN WITHOUT SED

SHW@SHW:/tmp/abc # cat a
https://git.centos.org/git/rpms/abc.git
https://git.centos.org/git/rpms/abc.git/
https://git.centos.org/git/rpms/abc
SHW@SHW:/tmp/abc # cat a | while read line; do basename $line .git; done
abc
abc
abc
0
0

I think the problem is the field separator of the awkcommand. Change the order, first the sed commands, than the awkcommand:

reponame=$(echo $url |  sed -e 's/.git\/$//' | sed -e 's/.git//' | awk -F/ '{print $NF}')
echo $reponame
2
  • I not no output with this. – sudhansh_ Mar 31 '16 at 10:47
  • @SudhanshAggarwal: sorry, there was a typo, the closing bracket was on the wrong place. – mnille Mar 31 '16 at 10:50
0
$ sed -E -e '\%(\.git|/)$%d' -e 's%.*/%%' file
abc

The sed script above first removes all lines from the input that ends with either / or the string .git. It then strips off everything from the remaining lines up to and including the last /.

Since the text we are dealing with contains /, we're using % as an alternative delimiter in the sed expressions.

If you want to extract abc from each line in the file:

$ sed -E -e 's%\.git/?$%%g' -e 's%.*/%%' file
abc
abc
abc

This first removes the string .git (possibly followed by a /) from the end of each line of input before applying the same substitution as in the first sed command.

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.