各コピーで1行を変更して、ファイルの複数のコピーを作成します。

各コピーで1行を変更して、ファイルの複数のコピーを作成します。

シミュレーションを自動化し、そのためにはシミュレーションごとに入力ファイルを生成する必要があります。私のシミュレーションのほとんどはほぼ同じで、1つのファイルから次のファイルにテキスト行が変更されます。特定の行が変更されたら、どのようにテキストファイルをインポートして複数のコピーを作成できますか?たとえば、テキストファイルに次のものが含まれているとします。

! input file
a = 6
b = 6
d = 789
! end

このテンプレートで6つの新しいファイルを作成したいのですが、後続の各ファイルで私の変数bが1ずつ減っているとしましょう。 BashまたはPythonでこれを行うにはどうすればよいですか?

ベストアンサー1

基本的なアプローチはこれと似ています。例では、a = value byenumber&file&filenameにも内部値があるため、区切りファイルに変更します。

#!/bin/bash


for i in a b c 1 2 3  ; do
    cat > file${i} << EOT
! input file
a = ${i}
b = 6
d = 789
! end
EOT
done

これにより、6つの異なるコンテンツを含む6つのファイルが得られます。

# cat file?
! input file
a = 1
b = 6
d = 789
! end
! input file
a = 2
b = 6
d = 789
! end
! input file
a = 3
b = 6
d = 789
! end
! input file
a = a
b = 6
d = 789
! end
! input file
a = b
b = 6
d = 789
! end
! input file
a = c
b = 6
d = 789
! end

たとえば、参照ファイルからb値を読み取る必要がある場合は、readサブコマンドで変数を使用できます。

while read ; do
cat > file${REPLY} << EOT
! input file
a = 1
b = ${REPLY}
d = 789
! end
EOT
done < referencefile

実際の状況の完全な例:

[root@h2g2w tmp]# cat > ./test.sh
while read ; do
cat > file${REPLY} << EOT
! input file
a = 1
b = ${REPLY}
d = 789
! end
EOT
done < referencefile


[root@h2g2w tmp]# cat > referencefile 
qsd
gfd
eza
vxcv
bxc
[root@h2g2w tmp]# 
[root@h2g2w tmp]# sh ./test.sh 
[root@h2g2w tmp]# ls -lrth file???
-rw-r--r--. 1 root root 41 28 juin  22:47 fileqsd
-rw-r--r--. 1 root root 41 28 juin  22:47 filegfd
-rw-r--r--. 1 root root 41 28 juin  22:47 fileeza
-rw-r--r--. 1 root root 41 28 juin  22:47 filebxc
[root@h2g2w tmp]# cat file???
! input file
a = 1
b = bxc
d = 789
! end
! input file
a = 1
b = eza
d = 789
! end
! input file
a = 1
b = gfd
d = 789
! end
! input file
a = 1
b = qsd
d = 789
! end
[root@h2g2w tmp]# 

今、あなたのニーズに合わせて調整できることを願っています。

おすすめ記事