0

我有一个来自同事的脚本来格式化我的提示。它使用 sed 使用下面的代码获取我的分支和格式(注意我硬编码了分支名称以进行测试):

echo "* master" | sed -e '/^[^*]/d' -e 's/* \(.*\)/ \1 /'

为了更多地了解脚本在做什么,我正在玩弄它。我注意到它打印了我的分支“master”的名称,但它在分支名称(“master”)之前留下了空格。我想消除空间。我似乎无法做到这一点。

4

4 回答 4

2

也许你正在寻找这个:

kent$  echo "* master" | sed 's/ \+//'                          
*master

此 sed 行删除第一次出现的一个或多个空格。

于 2013-11-24T22:14:57.333 回答
2

您可以通过不使用 sed 来简化问题

echo "* master" | cut -c3-
于 2013-11-24T22:09:22.503 回答
2

只需删除\1. 可能您也想删除它后面的空间。

echo "* master" | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/'
于 2013-11-24T22:55:26.737 回答
0

the original sed is a bit strange compare to your hard coding branch

  1. It delete the line if it not start with a "*" and try to load a new one. Your branch is coming from a file or command with multi line ?
  2. It take end of line after "* ". It is simplier to just "remove" begin of line

    Your_source | sed -n '/[^*]/ {s/^* //p;q;}'

take only line starting with "* ", remove begin, print it and quit (no more than 1 line starting with "* " treated)

于 2013-11-25T06:50:44.390 回答