Andrew
Andrew

Reputation: 33

How to use sed delete some lines of echo output

I want to remove some lines. I already have [email protected]:awg-roi-new/roi4cio-catalogs-fe.git and I need to leave only roi4cio-catalogs-fe. I used the next code but it isn't work proprely.

echo [email protected]:awg-roi-new/roi4cio-catalogs-fe.git | sed -r 's/.*\///' | sed -r 's/\.+//'

Upvotes: 2

Views: 160

Answers (4)

sseLtaH
sseLtaH

Reputation: 11207

Using sed

$ echo [email protected]:awg-roi-new/roi4cio-catalogs-fe.git | sed -r 's~.*/|\..*~~g'
roi4cio-catalogs-fe

Upvotes: 1

Gilles Quénot
Gilles Quénot

Reputation: 185025

Using awk:

echo [email protected]:awg-roi-new/roi4cio-catalogs-fe.git |
    awk -F'[/.]' '{print $3}'

Using sed:

echo [email protected]:awg-roi-new/roi4cio-catalogs-fe.git |
    sed -E 's|.*/([^\.]+)\..*|\1|' 

Using only bash:

IFS='/.' read _ _ var _ <<< [email protected]:awg-roi-new/roi4cio-catalogs-fe.git
echo "$var"

or using parameter expansion:

x='[email protected]:awg-roi-new/roi4cio-catalogs-fe.git'
x=${x%.git}
x=${x##*/}"
echo "$x"

Or using BASH_REMATCH:

[[ $x =~ /([^\.]+)\. ]] && echo "${BASH_REMATCH[1]}"

Using Perl:

echo [email protected]:awg-roi-new/roi4cio-catalogs-fe.git |
    perl -lne 'print $1 if m|/([^.]+)\.|'

Using grep:

echo [email protected]:awg-roi-new/roi4cio-catalogs-fe.git |
    grep -oP '(?<=/)([^.]+)'

Ouput

roi4cio-catalogs-fe

Upvotes: 1

RavinderSingh13
RavinderSingh13

Reputation: 133458

1st solution: With awk you could try following code. Where setting field separator(s) as .com OR / OR .git and printing 3rd field as per need.

echo "[email protected]:awg-roi-new/roi4cio-catalogs-fe.git" | 
awk -F'\\.com:|\\/|\\.git' '{print $3}'

2nd solution: Using GNU grep please try following solution.

echo "[email protected]:awg-roi-new/roi4cio-catalogs-fe.git" |
grep -oP '^.*?\/\K.*(?=\.git$)'

Upvotes: 2

The fourth bird
The fourth bird

Reputation: 163267

Your command does not give you the right result because you are repeating 1 or more times a dot here:

sed -r 's/.*\///' | sed -r 's/\.+//'
                              ^^^
                     

But you want to match 1 or more characters after the dot:

sed -r 's/.*\///' | sed -r 's/\..+//'
                              ^^^^ 

To keep only the part between the last / till before the last occurrence of a . you can use a single command with a capture group and a backreference:

echo [email protected]:awg-roi-new/roi4cio-catalogs-fe.git | 
    sed -E 's/.*\/([^/]+)\.[^./]+$/\1/'

Output

roi4cio-catalogs-fe

Upvotes: 3

Related Questions