Bash:配对两个系列的文件

Ein*_*nar 3 scripting bash shell-script

我有许多具有这种模式的文件:

file1_foo.ext
file1_bar.ext
file2_foo.ext
file2_bar.ext
Run Code Online (Sandbox Code Playgroud)

等等。

我需要“配对”并将它们放入这样的文件中

file1_foo.txt    file1_bar.txt
Run Code Online (Sandbox Code Playgroud)

(制表符分隔)

在这种情况下,最好的行动方案是什么?

Chr*_*own 6

我假设您不想假设两者都存在。如果它们都存在,这只会打印这些行。

for file1 in *_foo.ext; do
    file2="${file1%foo.ext}bar.ext"
    if [[ -e "$file2" ]]; then
        printf '%s\t%s\n' "$file1" "$file2"
    fi
done
Run Code Online (Sandbox Code Playgroud)

样本:

for file1 in *_foo.ext; do
    file2="${file1%foo.ext}bar.ext"
    if [[ -e "$file2" ]]; then
        printf '%s\t%s\n' "$file1" "$file2"
    fi
done
Run Code Online (Sandbox Code Playgroud)