【问题标题】:Substring string in bashbash中的子字符串
【发布时间】:2021-11-03 10:34:43
【问题描述】:

我得到了这个字符串:

xavier.blodot
wisoyo.hadi

我想要这个输出:firstletter+lastname

xblodot
whadi

问候!!

【问题讨论】:

    标签: linux bash shell substring


    【解决方案1】:
    name=xavier.blodot
    shortened_name="${name:0:1}${name##*.}"
    

    当名称不包含句点时,您将不得不抓住案例。

    【讨论】:

      【解决方案2】:

      标题说 in bash,所以我假设它必须在 bash only(不使用 sedawk 或其他外部进程):

      while read ns; do
        echo "${ns::1}${ns#*.}"
      done < the_input_file.txt
      

      如果需要,使其更具弹性取决于您。这取决于您(不)信任输入的程度。例如,这可能包括IFS= read -r ns[[ "$ns" == +([a-z]).+([a-z]) ]] 的检查以及任意其他一致性检查。

      【讨论】:

        【解决方案3】:

        再小一点sed:

        sed -E 's/^(.)[^.]+\./\1/' file
        
        xblodot
        whadi
        

        或者使用awk:

        awk -F. '{print substr($1,1,1) $2}' file
        
        xblodot
        whadi
        

        【讨论】:

          【解决方案4】:

          你应该使用这种方法:

          sed -r 's:(.).*\.(.+):\1\.\2:g' {YOUR_FILE.TXT}
          

          【讨论】:

          • 打印x.blodotw.hadi 而不是xblodotwhadi。也许只是在替换中删除\.
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-04-26
          • 2018-05-04
          • 2015-02-05
          • 2018-11-20
          • 1970-01-01
          • 2017-11-04
          • 2012-07-18
          相关资源
          最近更新 更多