选择字符串中的特定单词

时间:2013-01-06 07:44:16

标签: bash

string(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-文件758225 ZR67_op / Res-Edited-Files

我想只将以下内容收集到字符串(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将成为搜索元素

任何人都可以帮助我

2 个答案:

答案 0 :(得分: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"

答案 1 :(得分:0)

当你使用空格分隔的字符串,并且你在固定大小的集合(对,三元组等)中将字符串拉出字符串时,你可以使用'read'将标记加载到变量中:

#! /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