Bash 选择字符串中的特定单词

Bash 选择字符串中的特定单词,bash,Bash,字符串(contents1)包含以下内容 755572 ZR66_op/Res7.fcp 755676 ZR66_op/Res编辑的MP3文件755677 ZR66_op/Res文件756876 ZR66_op/Res编辑的WAV文件758228 ZR67_op/Res5.fcp 758224 ZR66_op/Res原始音频文件758225 ZR67_op/Res编辑的文件 我只想将以下内容收集到字符串中(contents2) 755572 ZR66_op/Res7.fcp 755676 ZR6

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

755572 ZR66_op/Res7.fcp 755676 ZR66_op/Res编辑的MP3文件755677 ZR66_op/Res文件756876 ZR66_op/Res编辑的WAV文件758228 ZR67_op/Res5.fcp 758224 ZR66_op/Res原始音频文件758225 ZR67_op/Res编辑的文件

我只想将以下内容收集到字符串中(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原始音频文件

ZR66_op
将是搜索元素


有人能帮我吗?你可以使用模式匹配:

#! /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"
#/bin/bash
搜索=ZR66_op
contents1=755572\ZR66\u op/Res7.fcp\\
755676\ZR66\u op/Res-Edited-MP3-Files\\
755677\ZR66\u op/Res文件\\
756876\ZR66\u op/Res编辑的WAV文件\\
758228\ZR67\u op/Res5.fcp\\
758224\ZR66 \u op/Res原始音频文件\\
758225\ZR67_op/Res编辑的文件
ar=($contents1)

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

#! /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
!/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原始音频文件758225 ZR67_op/Res Edited Files'
搜索=ZR66_op
contents2=“”
读取数字文件名时
做
如果[[$filename==“$search”*]]
然后
contents2=“$contents2$number$filename”
fi

在您的输出中完成,“755676”不包含“ZR66_op”。这是您的输出中的错误,还是与前面的字符串分组?(我假设您的字符串以空格分隔)。这将不会维护
contents2
变量:因为您正在将输入管道连接到while循环中,所以循环将在子shell中运行。子shell退出时,子shell中的任何变量更新都将丢失。您需要
while read…;完成了啊,胡说八道。我使用管道是因为我认为它更清晰…从未考虑过它会uld生成一个子外壳。相应地进行编辑。