Bash 如何合并两组后缀与文件名相同的文本文件?

Bash 如何合并两组后缀与文件名相同的文本文件?,bash,shell,unix,Bash,Shell,Unix,我有两组文件,第一组文件是: apple_sweet_1.txt apple_sweet_2.txt apple_sweet_3.txt 现在,我拥有的第二组文件是: mango_sweet_1.txt mango_sweet_2.txt mango_sweet_3.txt 我想在bash循环中对各个文件进行cat,这样我就可以得到类似这样的结果(当然,我不想单独这样做): bash解决方案: for f in apple_sweet_*.txt; do if [[ "$f" =~

我有两组文件,第一组文件是:

apple_sweet_1.txt
apple_sweet_2.txt
apple_sweet_3.txt
现在,我拥有的第二组文件是:

mango_sweet_1.txt
mango_sweet_2.txt
mango_sweet_3.txt
我想在bash循环中对各个文件进行cat,这样我就可以得到类似这样的结果(当然,我不想单独这样做):


bash
解决方案:

for f in apple_sweet_*.txt; do 
    if [[ "$f" =~ .*_([0-9]+).txt ]]; then 
        idx=${BASH_REMATCH[1]}              # getting file numeric index
        mango_fn="mango_sweet_${idx}.txt"   # related `mango` filename
        [ -f "$mango_fn" ] && cat "$f" "$mango_fn" > "sweet_${idx}.txt"
    fi
done

您可以将此
用于
循环:

for i in apple_sweet_*.txt; do
   p="${i#apple_}"
   [[ -f "mango_$p" ]] && cat "$i" "mango_$p" > "$p"
done
for i in apple_sweet_*.txt; do
   p="${i#apple_}"
   [[ -f "mango_$p" ]] && cat "$i" "mango_$p" > "$p"
done