【问题标题】:Modify bash string修改 bash 字符串
【发布时间】:2021-10-22 13:16:59
【问题描述】:

我是 bash 新手,在这个问题上需要帮助。

#!/bin/bash

str="This Is My Bash String"
mod="-val"

# Loop through characters of str. If index is 0, insert mod at position 0. And if the current index contains space (" "), then insert mod after the space.

echo -e str
# This should output: -valThis -valIs -valMy -valBash -valString

我怎样才能做到这一点?

【问题讨论】:

    标签: string bash


    【解决方案1】:

    使用 bash 和 Parameter Expansion:

    echo "$mod${str// / $mod}"
    

    输出:

    -valThis -valIs -valMy -valBash -valString

    【讨论】:

      【解决方案2】:
      for word in $str
      do echo -n " $mod$word"
      done
      

      【讨论】:

      【解决方案3】:

      参数扩展的替代方案:

      #!/usr/bin/env bash
      
      str="This Is My Bash String"
      mod="-val"
      
      # Split string words into an array
      IFS=' ' read -ra splitstr <<<"$str"
      
      # Print each element of array, prefixed by $mod
      printf -- "$mod%s " "${splitstr[@]}"
      printf \\n
      

      【讨论】:

        【解决方案4】:

        这也可能起到作用:

        echo $mod$str |sed -e "s/ / $mod/g"
        

        【讨论】:

          【解决方案5】:
          build_command_line() {
            local -ar tokens=(${@:2})
            printf '%s\n' "${tokens[*]/#/"$1"}"
          }
          

          现在让我们测试一下:

          mod='-val'
          str='This Is My Bash String'
          
          build_command_line "$mod" "$str"
          build_command_line "$mod" $str
          build_command_line "$mod" "$str" Extra Tokens
          build_command_line "$mod" $str 'Extra Tokens'
          

          要“修改”str,正如您指定的,只需重新分配它:

          str="$(build_command_line "$mod" "$str")"
          printf '%s\n' "$str"
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-09-26
            • 2014-05-30
            • 2018-04-10
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-10-04
            相关资源
            最近更新 更多