拆分字符串,提取字符并重新组合在一起

use*_*177 4 command-line bash scripts text-processing

我在的形式串wva/sia/e1bct/e2sv/de/e11。它总是 <Part1>/e<NUM><Part1>/<Part2>/e<NUM>。我想要的是通过保留部分的第一个字母并丢弃斜线和 e 来缩短字符串:

wva/sia/e1 > ws1
bct/e2 > b2
sv/de/e11 > sd11
Run Code Online (Sandbox Code Playgroud)

我怎样才能在 sh 脚本中做到这一点?

编辑:字符串表示作业名称:

[...]
job_name=$1 # e.g. 'wva/sia/e1'
job_name=cut_name(job_name) # e.g. 'ws1'
[...]
Run Code Online (Sandbox Code Playgroud)

Jac*_*ijm 5

脚本的形式作为您的要求:

#!/usr/bin/env python3
import sys

# read the input, split by /
st = sys.argv[1].split("/")
# get the first char of all sections *but* the last one
# add the last *from* the first character
print("".join([s[0] for s in st][:-1])+st[-1][1:])
Run Code Online (Sandbox Code Playgroud)

请注意,这适用于任何长度,例如:

wva/sia/bct/wva/sia/e1
Run Code Online (Sandbox Code Playgroud)

会变成

wsbws1
Run Code Online (Sandbox Code Playgroud)

只要最后一节以 /e<num>

使用

  1. 将脚本复制到一个空文件中,另存为 rearrange.py
  2. 使用字符串作为参数运行它,例如:

    python3 /path/to/rearrange.py wva/sia/e1
    
    > ws1
    
    Run Code Online (Sandbox Code Playgroud)

解释

该脚本几乎可以自我解释,但也有注释。