以成对方式连接文件

时间:2014-02-13 15:17:28

标签: bash shell concatenation zsh

我想以成对方式连接目录中的现有.txt文件 - 创建原始文件的所有可能组合。我不确定如何使用bashzsh shell scripting,而不是我的强项。我想有人需要将新文件输出到另一个目录,以防止组合的指数增加。

下面是一个虚拟的例子。实际上我有更多文件。

echo 'A' > A.txt
echo 'B' > B.txt
echo 'C' > C.txt

其中A + BB + A相同,订单没有重要性。

期望的输出:

>ls
AB.txt AC.txt BC.txt

>head AB.txt
# A
# B
>head AC.txt
# A
# C
>head BC.txt
# B
# C

以下是尝试(某事......)

#!/bin/zsh

counter = 1
for i in *.txt; do
    cat $i $counter $i
done

任何指针都会受到高度赞赏。

3 个答案:

答案 0 :(得分:2)

您可以使用简单的嵌套循环来解决它

for a in *; do
  for b in *; do
     cat "$a" "$b" > "${a%.txt}$b"
  done
done

你可以尝试一种递归方法

#!/bin/bash -x

if [ $# -lt 5   ]; then
   for i in *.txt; do
      $0 $* $i;
   done;
else
  name=""

  for i ; do
    name=$name${i%.txt}
  done
  cat $* >> $name.txt
fi;

答案 1 :(得分:1)

zsh中,您可以执行以下操作:

filelist=(*.txt)
for file1 in $filelist; do
    filelist=(${filelist:#$file1})
    for file2 in $filelist; do
        cat "$file1" "$file2" > "${file1%.txt}$file2"
    done
done

<强>解释

*.txt中存储filelist的列表,周围的括号使其成为一个数组:

filelist=(*.txt)

filelist的{​​{1}}中的所有元素进行迭代:

file1

for file1 in $filelist; do 移除file1

filelist

filelist=(${filelist:#$file1})

filelist的剩余元素进行迭代
file2

连接 for file2 in $filelist; do file1。保存到具有组合名称的新文件中(从第一个文件名的末尾删除file2。)

.txt

答案 2 :(得分:0)

Python很容易。将其放在具有可执行权限的/usr/local/bin/pairwise中:

#!/usr/bin/env python

from itertools import combinations as combo
import errno
import sys

data = sys.stdin.readlines()

for pair in combo(data, 2):
    try:
        print pair[0].rstrip('\n'), pair[1].rstrip('\n')
    except OSError as exc:
        if exc.errno = errno.EPIPE:
            pass
        raise

然后试试这个:

seq 4 | pairwise

导致:

1 2
1 3
1 4
2 3
2 4
3 4

或试试这个:

for x in a b c d e; do echo $x; done | pairwise

导致:

a b
a c
a d
a e
b c
b d
b e
c d
c e
d e
相关问题