Reputation: 31
string (contents1) contains the following
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
I want to collect only the following into string (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
the ZR66_op
will be the search element
Can any one help me in this
Upvotes: 3
Views: 128
Reputation: 4416
When you are working with a whitespace delimited string, and you are pulling tokens off the string in fixed sized sets (pairs, triples, etc.), you can use 'read' to load the tokens into variables:
#! /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
Upvotes: 0
Reputation: 241768
You can use pattern matching:
#! /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"
Upvotes: 2