如何正确使用 cut 从 shell 脚本中的字符串中获取所需的输出?

Sar*_*mar 1 bash shell cut

#!/bin/bash
list="john,do not target
martin,unknown"

for i in $list; do
     name=`echo ${i} | cut -f1 -d','`
     value=`echo ${i} | cut -f2 -d','`
     echo $value
done
Run Code Online (Sandbox Code Playgroud)

由于中间的空白不以我得到的上述输出为目标,

do
not
target
unknown
Run Code Online (Sandbox Code Playgroud)

我想要的输出是:

do not target
unknown
Run Code Online (Sandbox Code Playgroud)

And*_*mek 5

不需要cut(外部过程);你可以在 Bash 中执行此操作:

list='john,do not target
martin,unknown'

while IFS= read -r line; do
    name="${line%%,*}"
    value="${line#*,}"
    printf "'%s' : '%s'\n" "$name" "$value"
done <<< "$list"
Run Code Online (Sandbox Code Playgroud)

但是,除非list来自您无法控制的输入(就格式而言),否则有更好的方法在 Bash 中表示此类数据,例如关联数组。

declare -A list=(
    ['john']='do not target'
    ['martin']='unknown'
)

for name in "${!list[@]}"; do
    printf "'%s' : '%s'\n" "$name" "${list["$name"]}"
done
Run Code Online (Sandbox Code Playgroud)

诚然,关联数组不保留顺序;如果需要的话,您可以有一个从数字到名称的附加(整数索引)数组映射。

declare -a list=('john' 'martin')
declare -A data=(
    ['john']='do not target'
    ['martin']='unknown'
)

for name in "${list[@]}"; do
    printf "'%s' : '%s'\n" "$name" "${data["$name"]}"
done
Run Code Online (Sandbox Code Playgroud)


mar*_*rkp 5

read我们为我们进行分割(通过IFS):

while IFS=, read -r name value      # split line of input on a comma; store 1st field in variable 'name', store rest of input in variable 'value'
do
    echo "${value}"
done <<< "${list}"
Run Code Online (Sandbox Code Playgroud)

注意:这具有消除当前代码在每次循环时生成的 4 个子进程的额外好处

这会生成:

do not target
unknown
Run Code Online (Sandbox Code Playgroud)