Bash:如何从字符串中删除多个前缀变量

时间:2015-10-30 21:15:31

标签: bash sed

我试图删除使用bash从package.json文件解析的url字符串的前缀。我发现的问题是并非每个人都进入存储库:url始终在他们的包文件中。

e.g:

git+https://github.com/<USER>/<REPO>.git

https://github.com/<USER>/<REPO>.git

我也发现:

http://github.com/<USER>/<REPO>.git

所以我的问题是,如何删除可能在.json中找到的字符串前缀?以下是我未能成功的尝试。

repo_url="`node -pe 'JSON.parse(process.argv[1]).repository.url' "$(cat $pkg_json)"`"

repo=${repo_url#git+}
repo=${repo_url#https://github.com/}
repo=${repo%.git}
echo "${repo}"

更新

我发现在前缀之前添加一个通配符将消除前缀之前的所有内容。但是我如何处理http

e.g:

repo=${repo_url#*https://github.com/}

2 个答案:

答案 0 :(得分:1)

Each of your assignments to repo uses the original $repo_url as the source, so the removals from the previous assignment aren't maintained. You should use $repo as the source, except for the first one:

repo_url="`node -pe 'JSON.parse(process.argv[1]).repository.url' "$(cat $pkg_json)"`"

repo=${repo_url#git+}
repo=${repo#https://github.com/}
repo=${repo%.git}
echo "${repo}"

答案 1 :(得分:1)

An awk alternative:

echo $repo_url|awk  '{print $(NF-2)"/"$(NF-1)}' FS='[./]'

repo="`node -pe 'JSON.parse(process.argv[1]).repository.url' "$(cat $pkg_json)" | awk  '{print $(NF-2)"/"$(NF-1)}' FS='[./]'`"