3

字符串(contents1)包含以下内容

755572 ZR66_op/Res7.fcp 755676 ZR66_op/Res-Edited-MP3-Files 755677 ZR66_op/Res-Files 756876 ZR66_op/Res-Edited-WAV-Files 758228 ZR67_op/Res5.fcp 758224 ZR67_alop/ResFile-Files /Res-Edited-文件

我只想将以下内容收集到字符串中(contents2)

755572 ZR66_op/Res7.fcp 755676 ZR66_op/Res-Edited-MP3-Files 755677 ZR66_op/Res-Files 756876 ZR66_op/Res-Edited-WAV-Files 758224 ZR66_op/Res-Original-Audio-Files

ZR66_op是搜索元素

任何人都可以帮助我吗

4

2 回答 2

2

您可以使用模式匹配:

#! /bin/bash
search=ZR66_op

contents1=755572\ ZR66_op/Res7.fcp\ \
755676\ ZR66_op/Res-Edited-MP3-Files\ \
755677\ ZR66_op/Res-Files\ \
756876\ ZR66_op/Res-Edited-WAV-Files\ \
758228\ ZR67_op/Res5.fcp\ \
758224\ ZR66_op/Res-Original-Audio-Files\ \
758225\ ZR67_op/Res-Edited-Files

ar=($contents1)

for (( i=0; i/2<=${#ar}; i+=2 )) ; do
    if [[ ${ar[i+1]} == "$search"* ]] ; then
        contents2+="${ar[i]} ${ar[i+1]} "
    fi
done

contents2=${contents2% } # Remove the extra space
echo "$contents2"
于 2013-01-06T10:29:20.530 回答
0

当您使用以空格分隔的字符串时,并且您正在从字符串中提取固定大小的集合(对、三元组等)中的标记时,您可以使用“读取”将标记加载到变量中:

#! /bin/bash
contents1='755572 ZR66_op/Res7.fcp 755676 ZR66_op/Res-Edited-MP3-Files 755677 ZR66_op/Res-Files 756876 ZR66_op/Res-Edited-WAV-Files 758228 ZR67_op/Res5.fcp 758224 ZR66_op/Res-Original-Audio-Files 758225 ZR67_op/Res-Edited-Files'

search=ZR66_op

contents2=""
while read number filename
do
    if [[ $filename == "$search"* ]]
    then
        contents2="$contents2 $number $filename "
    fi
done <<< $contents1

echo $contents2
于 2013-01-06T17:01:20.167 回答