简体   繁体   English

如何使用sed删除echo output的部分行

[英]How to use sed delete some lines of echo output

I want to remove some lines.我想删除一些行。 I already have git@gitlab.com:awg-roi-new/roi4cio-catalogs-fe.git and I need to leave only roi4cio-catalogs-fe .我已经有了git@gitlab.com:awg-roi-new/roi4cio-catalogs-fe.git我只需要留下roi4cio-catalogs-fe I used the next code but it isn't work proprely.我使用了下一个代码,但它不能正常工作。

echo git@gitlab.com:awg-roi-new/roi4cio-catalogs-fe.git | sed -r 's/.*\///' | sed -r 's/\.+//'

Your command does not give you the right result because you are repeating 1 or more times a dot here:您的命令没有给您正确的结果,因为您在这里重复了 1 次或多次:

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

But you want to match 1 or more characters after the dot:但是您想在点之后匹配 1 个或多个字符:

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

To keep only the part between the last / till before the last occurrence of a .只保留 a 的最后一次出现之前/之间的部分. you can use a single command with a capture group and a backreference:您可以使用带有捕获组和反向引用的单个命令:

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

Output Output

roi4cio-catalogs-fe

1st solution: With awk you could try following code.第一个解决方案:使用awk您可以尝试以下代码。 Where setting field separator(s) as .com OR / OR .git and printing 3rd field as per need.将字段分隔符设置为.com OR / OR .git并根据需要打印第三个字段。

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

2nd solution: Using GNU grep please try following solution.第二个解决方案:使用 GNU grep请尝试以下解决方案。

echo "git@gitlab.com:awg-roi-new/roi4cio-catalogs-fe.git" |
grep -oP '^.*?\/\K.*(?=\.git$)'

Using awk :使用awk

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

Using sed :使用sed

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

Using only bash :仅使用bash

IFS='/.' read _ _ var _ <<< git@gitlab.com:awg-roi-new/roi4cio-catalogs-fe.git
echo "$var"

or using parameter expansion :或使用参数扩展

x='git@gitlab.com:awg-roi-new/roi4cio-catalogs-fe.git'
x=${x%.git}
x=${x##*/}"
echo "$x"

Or using BASH_REMATCH :或者使用BASH_REMATCH

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

Using Perl :使用Perl

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

Using grep :使用grep

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

Ouput输出

roi4cio-catalogs-fe

Using sed使用sed

$ echo git@gitlab.com:awg-roi-new/roi4cio-catalogs-fe.git | sed -r 's~.*/|\..*~~g'
roi4cio-catalogs-fe

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM