如何编写shell脚本,自动进行文件转换?

时间:2016-06-17 13:52:19

标签: linux bash shell sh csh

我有30个文件(ascii),我想将其转换为已编译的binary.Linux命令行(FORTRAN 77 CODE)

int

代码的相关部分

./rec_binary 

然后代码要求输入和输出文件名

      character*72 ifname,ofname
c
      write(*, fmt="(/'Enter input file name')")
      read(5,85) ifname
85    format(a72)
      write(*, fmt="(/'Enter output file name')")
      read(5,85) ofname

如何自动化?我试过这样的

Enter input file name
rec01.txt

Enter output file name
rec.01

或者

#!/bin/csh -f
set list = 'ls rec*.txt'
foreach file ($list)
rec_binary ${file} > 

但是我没有下一步的线索。文本文件是

#!/bin/sh
for f in .txt
do
./rec_binary F
done

输出文件

rec01.txt
rec02.txt

rec30.txt

3 个答案:

答案 0 :(得分:2)

试试这个:

#!/bin/bash
for each in `ls rec*.txt`
do
  op_file=$(echo $each | sed 's/\(rec\)\([0-9]*\).txt/\1\.\2/')
  ./rec_binary <<EOF
$each
$op_file
EOF
done

变量op_file将您的rec01.txt转换为rec.01。

答案 1 :(得分:1)

假设您了解rec_binary。我不确定它做了什么。我是根据你提出的输入做出来的。

for i in rec*.txt;
 do
    rec_binary "$i"
done

答案 2 :(得分:0)

有很多不同的方法可以做到这一点。一种方法是使用for循环,但是,不清楚你所显示的rec_binary命令是否允许参数。

for i in rec*.txt; do
    num=$( echo $i | egrep -o "\d+" )
    echo ${i} > "rec.${num}"
done 

如果您可以从命令行./rec_binary file1 file2执行此类操作,那么这应该可行。如果rec_binary命令回显到标准输出,那么您可以将其发送到文件:

for i in rec*.txt; do
    num=$( echo $i | egrep -o "\d+" )
    rec_binary ${i} > "rec.${num}"
done

$num变量只是在循环时从文件名中捕获数字,然后我们可以在运行下一个命令时使用它来构造文件名。