Powershell切断回购名称

时间:2018-07-19 12:05:45

标签: arrays string powershell

我在文件中有一个字符串:

> dput(dtt)
structure(list(V1 = c("2009-01-13", "2009-01-14", "2009-01-15", 
"2009-01-16", "2009-01-19", "2009-01-27", "2009-01-30", "2009-02-02", 
"2009-02-09", "2009-02-12", "2009-02-13", "2009-02-16", "2009-02-17", 
"2009-02-27", "2009-03-02", "2009-03-12", "2009-03-13", "2009-03-17", 
"2009-03-18", "2009-03-20"), V2 = c("09:55:00", "09:55:00", "09:55:00", 
"09:55:00", "09:55:00", "09:55:00", "09:55:00", "09:55:00", "09:55:00", 
"09:55:00", "09:55:00", "09:55:00", "09:55:00", "09:55:00", "09:55:00", 
"09:55:00", "09:55:00", "09:55:00", "09:55:00", "09:55:00"), 
    V3 = c(4645, 4767.5, 4485, 4580, 4532, 4190, 4436, 4217, 
    4469, 4469.9, 4553, 4347.2, 4161.05, 3875.55, 3636, 3420, 
    3656, 3650, 3721, 3687), V4 = c(4838.931, 4718.254, 4653.316, 
    4537.693, 4548.088, 4183.503, 4155.236, 4152.626, 4203.437, 
    4220.845, 4261.98, 4319.656, 4371.474, 3862.085, 3846.423, 
    3372.665, 3372.1, 3360.421, 3363.735, 3440.651), V5 = c(5358.883, 
    5336.703, 5274.384, 5141.435, 4891.041, 4548.497, 4377.907, 
    4390.802, 4376.277, 4503.798, 4529.777, 4564.387, 4548.912, 
    4101.929, 4036.02, 3734.949, 3605.357, 3663.322, 3682.293, 
    3784.778), V6 = c("Buy2", "Buy1", "Buy2", "Buy1", "Buy2", 
    "Buy1", "Sell1", "Sell2", "Sell1", "Sell2", "Sell1", "Sell2", 
    "Buy2", "Buy1", "Buy2", "Buy1", "Sell1", "Sell2", "Sell1", 
    "Sell2")), row.names = c(NA, -20L), class = "data.frame")

我只需要从此字符串中删除回购名称(Myrepo,Mysecondrepo,Myrepo-old)。如何在Powershell中执行此操作?

我尝试过:

git@github.com:myorg/Myrepo.git
git@github.com:myorg/Mysecondrepo.git
git@github.com:myorg/Myrepo-old.git

但是它总是返回我git@github.com:myorg。如何重写这段代码?

2 个答案:

答案 0 :(得分:2)

像这样尝试:

foreach($link in $gitlink)
{
    $s = $link.Split('/')[1].TrimEnd('.git')
    echo $s
}

说明:

  1. Split('/')将字符串分为两部分
  2. [1]选择/之后的部分
  3. TrimEnd('.git')剪切字符串中的最后一个.git

作为替代方案,您可以尝试这样做:

foreach($link in $gitlink)
{
    $s = $link.Substring(($link.IndexOf('/')+1) , ($link.Length - $link.IndexOf('/') -5))
    echo $s
}

答案 1 :(得分:2)

您可以将正则表达式与(捕获组)一起使用,以直接剥离所有内容并仅保留存储库名称。

$Repos = (Get-Content '.\gitlinks.txt') -replace '^.*/(.*)\.git$','$1'
$Repos

Myrepo
Mysecondrepo
Myrepo-old

编辑:从scrrenshot合并到脚本中

## Q:\Test\2018\07\19\SO_51423853.ps1
Set-Location 'C:\a\'

ForEach($link in $gitlink){
    git clone $link
    $repodir = $link -replace '^.*/(.*)\.git$','$1'
    $repodir
    Push-Location $repodir
    git --no-pager --oneline --before 2018-07-1 --after 2012-06-10 | 
        Out-File -FilePath c:\a\commits.txt
    Pop-Location
}