【问题标题】:bash loop exchange placeholder in text file文本文件中的bash循环交换占位符
【发布时间】:2020-12-16 23:11:46
【问题描述】:

我是 bash 新手,我试图找到问题的答案:

我有 5 列的 text_file_A a。第一列是“名称”(类似于:6xr8),其余列是数字。此 text_file_A 由 3 行组成,其中第一列中的“名称”没有变化,只有以下列中的数字。

然后我有第二个 text_file_B,其中有 5 个占位符 $1、$2、$3、$4、$5。此文本文件用于运行program_A。我可以用/path_to_program/program_A text_file_B 执行程序。

现在我想要一个bash脚本,它读取text_file_A的第一行并替换text_file_B中的占位符并生成一个output_file,可以由program_A执行。

text_file_C 中读取变量并使用while 循环执行program_C 没有问题:

#! /bin/sh

file="text_file_C.txt"

while IFS= read line
do
    #echo "$line"
    ./program_C.sh $line
done<"$file"

但是上面有 2 个文本文件的问题我无法解决。

更详细地说,我想遍历text_file_A 的所有行。该文件如下所示:

6xr8      5000   0.1    100 200
6xr8      5000   0.3    300 200
6xr8      5000   0.5    500 200

其中第 1 列指向 $1,第 2 列指向 $2,第 3 列指向 $3,第 4 列指向 $4,第 5 列指向 $5。现在我想要一个脚本,它将text_file_A 第一行中的所有值替换为text_file_B 中的$1、$2、$3、$4、$5 并写出text_file_C,然后它为第二行以此类推……

文件text_file_B 如下所示:

=== simulation ===
generate_micrographs = yes

log_file = $1_file.log

=== sample ===

diameter = 500

thickness_center = 50

thickness_edge = 50

=== particle $1 ===

source = pdb

pdb_file_in = $1.pdb

voxel_size = 0.1

map_file_re_out = $1_map.mrc

map_file_im_out = $1_abs_map.mrc

=== particleset ===

particle_type = $1

particle_coords = file

coord_file_in = $1_coordinates.txt

num_particles = $5

where = volume

coord_file_out = $1_coordinates_1.txt

=== electronbeam ===

acc_voltage = 300

energy_spread = 0.7

gen_dose = yes

dose_per_im = $2

=== optics ===

magnification = 50926.86902

cs = 2.7

cc = 2.7

aperture = 300

focal_length = 3.5

cond_ap_angle = 0.05

gen_defocus = yes

defocus_nominal = $3

=== detector ===

det_pix_x = 4000

det_pix_y = 4000 

pixel_size = 5

gain = 1

use_quantization = yes

dqe = 1

mtf_a = 0

mtf_b = 0.935

mtf_c = 0

mtf_alpha = 0

mtf_beta = 0.64

image_file_out = $1_09818_$4_P$5_$2eA.mrc

【问题讨论】:

  • 我不明白你在做什么。您能否展示文件示例以及结果应该是什么?
  • 你只想阅读text_file_A的第一行,而不是遍历所有行?

标签: bash loops variables text placeholder


【解决方案1】:

text_file_A这一行读入一组变量。然后使用带有sed 的那些来替换text_file_B 中的占位符。

read -r col1 col2 col3 col4 col5 < text_file_A
sed -e 's/\$1/'"$col1/" -e 's/\$2/'"$col2/" -e 's/\$3/'"$col3/" -e 's/\$4/'"$col4/" -e 's/\$5/'"$col5/" text_file_B > text_file_C

要遍历text_file_A 中的行,...添加一个循环,如下所示:

while read -r col1 col2 col3 col4 col5; do
    sed -e 's/\$1/'"$col1/" -e 's/\$2/'"$col2/" -e 's/\$3/'"$col3/" -e 's/\$4/'"$col4/" -e 's/\$5/'"$col5/" text_file_B > text_file_C
    /path_to_program/program_A text_file_C
done <text_file_A

【讨论】:

  • while 循环中有一个小错字,您在其中指定 col2。
猜你喜欢
  • 1970-01-01
  • 2010-09-29
  • 2013-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多