AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / unix / 问题 / 794192
Accepted
Cestarian
Cestarian
Asked: 2025-04-26 11:54:13 +0800 CST2025-04-26 11:54:13 +0800 CST 2025-04-26 11:54:13 +0800 CST

使用花括号处理冒号分隔的变量

  • 772

如果我们这样做:

VAR=100:200:300:400

我们可以做到:

echo ${VAR%%:*}
100

和

echo ${VAR##*:}
400

是否有任何等价物可以用来获取 200 和 300 的值?

例如,如果有超过 3 个冒号,是否有办法只获取第二个和第三个冒号之间的内容?

bash
  • 4 4 个回答
  • 353 Views

4 个回答

  • Voted
  1. Best Answer
    Stéphane Chazelas
    2025-04-26T15:26:57+08:002025-04-26T15:26:57+08:00

    ksh 样式(现在由 POSIX 为 sh 指定)${var#pattern}和(以及带有和 的${var%pattern}贪婪变体)仅从变量内容的开头和结尾分别删除文本。##%%

    要200摆脱100:200:300:400这些操作符,您需要同时应用从开头${VAR#*:}删除和从结尾删除。100:${VAR%%:*}:300:400

    那将是${${VAR#*:}%%:*},但虽然那可以在 zsh 中起作用,但在 bash 或 ksh 中不起作用,因为不允许链接参数扩展运算符。

    在中zsh,您宁愿使用$VAR[(ws[:])2]来获取¹的2第n个 : s分隔的w顺序$var,或者使用${${(s[:])VAR}[2]}先将变量拆分为数组,然后获取第二个元素。

    在 ksh93 中,您可以执行${VAR/*:@(*):*:*/\1},但是虽然 bash(如 zsh²)复制了 ksh93 的${param/pattern/replacement}操作符,但它并没有复制捕获和引用部分。

    在 bash 中(尽管存在种种限制,但由于它是 GNU shell,因此仍然被广泛使用,几乎预装在所有的 GNU/Linux 系统以及一些非 GNU 系统上),您可以通过两个步骤完成此操作:

    tmp=${VAR#*:}; printf '%s\n' "${tmp%%:*}"
    

    bash 的唯一内置拆分运算符(除非您想考虑 bash 4.4+,readarray -d它更多地用于将记录从某些输入流读取到数组中;以及通过在其语法中分离出参数来进行的拆分类型)是 Bourne 风格(由 Korn 扩展)IFS 拆分,它是在未引用的扩展上执行的(您在echo ${VAR%%:*}忘记引号的地方错误地使用了它),并且通过read。

    read只在一行上起作用,因此只能用于不包含换行符的变量。使用 split+glob(glob 是扩展名不加引号的另一个副作用)很麻烦,因为我们需要禁用 glob 部分,并更改全局$IFS参数。

    在 bash 4.4+ 中,你可以这样做:

    nth() {
      local - # local - is to make the changes to option settings local to
              # the function like in the Almquist shell. The idea is that it
              # makes the $- special parameter local to the function. That's
              # equivalent to the set -o localoptions of zsh. In bash, that
              # only works for the set of option managed by set, not the ones
              # managed by shopt.
      local string="$1" n="$2" IFS="${3- }"
      set -o noglob # disable the glob part
      set -- $string''   # apply split+glob with glob disabled
      printf '%s\n' "${!n}" # dereference the parameter whose name is stored in $n
    }
    nth "$VAR" 2 :
    

    如果没有'',100::300:则只会拆分为“100”、“”和“300”,因此,$#即使变量包含 4 个:分隔的字段,也会扩展为 3。但请注意,这意味着空变量会被拆分为 1 个空元素,而不是 0。

    对于read( 或readarray) ,类似的解决方法是在输入末尾添加一个额外的分隔符。由于 bash 变量(与 zsh 相反)无论如何都不能包含 NUL 字符,因此对于read任意变量值,您可以执行以下操作:

    words=()
    IFS=: LC_ALL=C read -rd '' -a words < <(printf '%s:\0' "$VAR") &&
      printf '%s\n' "${word[2 - 1]}"
    

    (- 1因为read从索引 0 而不是 1 开始填充数组;LC_ALL=C解决了bash 版本 5.0 到 5.2 中未按用户编码编码的文本的一些错误)

    使用readarray(bash 4.4):

    records=()
    readarray -O1 -td : records < <(printf %s: "$VAR") &&
      printf '%s\n' "${records[2]}"
    

    再次,:在末尾添加以防止丢弃尾随的空元素(但再次意味着空输入会导致一个空元素)。


    ¹ 不过请注意,它会拆分::a:b::c:::成a,b并且c仅像 Bourne shell 中的 IFS 拆分那样(但在现代 Bourne 类 shell 中则不会,除非使用空格、制表符或换行符作为分隔符)。

    ² zsh 支持它,但语法不同,并且需要extendedglob启用该选项:${VAR/(#b)*:(*):*:*/$match[1]}

    • 12
  2. Sotto Voce
    2025-04-26T13:44:58+08:002025-04-26T13:44:58+08:00

    我不会尝试对冒号分隔的字符串值使用替换语法。相反,我使用拆分将冒号之间的部分放入数组中,然后执行变量替换(甚至数组切片)以返回所需的数组元素:

    #!/usr/bin/env bash
    VAR='100:200:300:400'
    
    IFS=: read -ra VAR2 <<<"$VAR"
    
    echo "${VAR}"
    echo "${VAR2[1]}"
    echo "${VAR2[@]}"
    echo "${VAR2[@]:1:2}"
    

    产生输出:

    100:200:300:400
    200
    100 200 300 400
    200 300
    

    如果原始值中的冒号之间也出现空格字符(您应该仔细测试这些内容),这可能不会产生您想要的精确效果,但您的示例中没有任何空格字符。

    • 6
  3. userene
    2025-04-26T18:13:20+08:002025-04-26T18:13:20+08:00

    您可以使用 IFS 并设置来分离和访问所有四个:

    $ VAR=100:200:300:400
    $ IFS=:
    $ set -- $VAR
    $ echo $1
    100
    $ echo $2
    200
    $ echo $3
    300
    $ echo $4
    400
    
    • 6
  4. Jetchisel
    2025-04-26T14:33:33+08:002025-04-26T14:33:33+08:00

    例如,如果有超过 3 个冒号,如何只获取第二个和第三个冒号之间的内容?

    这需要手动扩展大量的参数。你可以使用分隔符循环遍历,例如

    #!/bin/sh
    
    counter=0
    var='100:200:300:400'
    
    while [ -n "$var" ]; do   ##: Test if $var is not empty.
      first="${var%%:*}"      ##: Extract the first string sep by a `:'
      rest=${var#*"$first"}   ##: Remove the first string sep by a `:'
      var="${rest#:}"         ##: Remove the first occurence of `:'
      counter=$((counter+1))  ##: Increment the counter by one
    
       case "$counter" in
         (2|3) printf '%s\n' "$first";;   ##: Counter reached the 2nd and 3rd field, print it
         (4) break ;;                     ##: Break the loop from the 4th field (if there are more)
       esac                               ##: Repeat the while loop until the condition is met.
     done                                 ##: which is until $var is empty.
    

    输出:

    200
    300
    

    loadable builtin使用已调用该函数的 Bash 版本dsv,可以像上面那样解析字符串cut。您可以尝试以下操作:

    #!/usr/bin/env bash
    
    enable dsv || exit
    
    var='1 00:20 0:300 : 4 0 0 '
    
    dsv -a array -d':' "$var"
     
    declare -p array
    

    输出:

    declare -a array=([0]="1 00" [1]="20 0" [2]="300 " [3]=" 4 0 0 ")
    

    如果某些字段为空,如下所示:

    var='1 00::200:300 : 4 0 0 '
    

    该-g选项可用于跳过/删除它。

    dsv -a array -gd':' "$var"
    

    在某些情况下,输入可以有如下所示的双引号字段。

    解析理解并跳过双引号字符串。

    var='1 00:"20:0":300 : 4 0 0 '
    

    输出:

    declare -a array=([0]="1 00" [1]="20:0" [2]="300 " [3]=" 4 0 0 ")
    

    • 可加载内置程序是一个单独的包,据我所知bash它不包含在内。

    根据help dsv

    dsv: dsv [-a ARRAYNAME] [-d DELIMS] [-Sgp] string
        Read delimiter-separated fields from STRING.
        
        Parse STRING, a line of delimiter-separated values, into individual
        fields, and store them into the indexed array ARRAYNAME starting at
        index 0. The parsing understands and skips over double-quoted strings. 
        If ARRAYNAME is not supplied, "DSV" is the default array name.
        If the delimiter is a comma, the default, this parses comma-
        separated values as specified in RFC 4180.
        
        The -d option specifies the delimiter. The delimiter is the first
        character of the DELIMS argument. Specifying a DELIMS argument that
        contains more than one character is not supported and will produce
        unexpected results. The -S option enables shell-like quoting: double-
        quoted strings can contain backslashes preceding special characters,
        and the backslash will be removed; and single-quoted strings are
        processed as the shell would process them. The -g option enables a
        greedy split: sequences of the delimiter are skipped at the beginning
        and end of STRING, and consecutive instances of the delimiter in STRING
        do not generate empty fields. If the -p option is supplied, dsv leaves
        quote characters as part of the generated field; otherwise they are
        removed.
        
        The return value is 0 unless an invalid option is supplied or the ARRAYNAME
        argument is invalid or readonly.
    
    • 5

相关问题

  • 通过命令的标准输出以编程方式导出环境变量[重复]

  • 从文本文件传递变量的奇怪问题

  • 虽然行读取保持转义空间?

  • `tee` 和 `bash` 进程替换顺序

  • 运行一个非常慢的脚本直到它成功

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    模块 i915 可能缺少固件 /lib/firmware/i915/*

    • 3 个回答
  • Marko Smith

    无法获取 jessie backports 存储库

    • 4 个回答
  • Marko Smith

    如何将 GPG 私钥和公钥导出到文件

    • 4 个回答
  • Marko Smith

    我们如何运行存储在变量中的命令?

    • 5 个回答
  • Marko Smith

    如何配置 systemd-resolved 和 systemd-networkd 以使用本地 DNS 服务器来解析本地域和远程 DNS 服务器来解析远程域?

    • 3 个回答
  • Marko Smith

    dist-upgrade 后 Kali Linux 中的 apt-get update 错误 [重复]

    • 2 个回答
  • Marko Smith

    如何从 systemctl 服务日志中查看最新的 x 行

    • 5 个回答
  • Marko Smith

    Nano - 跳转到文件末尾

    • 8 个回答
  • Marko Smith

    grub 错误:你需要先加载内核

    • 4 个回答
  • Marko Smith

    如何下载软件包而不是使用 apt-get 命令安装它?

    • 7 个回答
  • Martin Hope
    user12345 无法获取 jessie backports 存储库 2019-03-27 04:39:28 +0800 CST
  • Martin Hope
    Carl 为什么大多数 systemd 示例都包含 WantedBy=multi-user.target? 2019-03-15 11:49:25 +0800 CST
  • Martin Hope
    rocky 如何将 GPG 私钥和公钥导出到文件 2018-11-16 05:36:15 +0800 CST
  • Martin Hope
    Evan Carroll systemctl 状态显示:“状态:降级” 2018-06-03 18:48:17 +0800 CST
  • Martin Hope
    Tim 我们如何运行存储在变量中的命令? 2018-05-21 04:46:29 +0800 CST
  • Martin Hope
    Ankur S 为什么 /dev/null 是一个文件?为什么它的功能不作为一个简单的程序来实现? 2018-04-17 07:28:04 +0800 CST
  • Martin Hope
    user3191334 如何从 systemctl 服务日志中查看最新的 x 行 2018-02-07 00:14:16 +0800 CST
  • Martin Hope
    Marko Pacak Nano - 跳转到文件末尾 2018-02-01 01:53:03 +0800 CST
  • Martin Hope
    Kidburla 为什么真假这么大? 2018-01-26 12:14:47 +0800 CST
  • Martin Hope
    Christos Baziotis 在一个巨大的(70GB)、一行、文本文件中替换字符串 2017-12-30 06:58:33 +0800 CST

热门标签

linux bash debian shell-script text-processing ubuntu centos shell awk ssh

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve