2014-11-03 50 views
-1

我有这种形式的输入文件:Linux的读取文件中的行,并传递到另一个程序

Some text here 
Another text here 
Something else here 

现在我想编写Linux脚本输入文件中选取一条线的时间和创建单独存储收到的行的文件。在此之后,我想将这个文件传递给一个程序(为此我只有二进制文件)。是否有可能编写这样的Linux脚本。我习惯于用C++编程,我知道它可能在那里。但我想知道是否可以使用Linux脚本。基本上,我打算做到以下几点:

read inputfile.txt line by line 
     store line read in inputFileInside.txt 
     ./myprogram paramater1 inputFileInside.txt //run my C++ binary file which I usually run as (root$./myprogram parameter1 inputFileInside.txt) 
     sudo sh -c \"sync; echo 3 > /proc/sys/vm/drop_caches\" 
exit when the input file has been read 
+0

您可以分解“逐行读取文件并将行存储在文本文件中”设置为1. [逐行读取文件](http://stackoverflow.com/questions/10929453/bash-scripting - 逐行读取文件)和2. [将文本写入文件](http://stackoverflow.com/questions/11162406/open-and-write-data-on-text-file-by -bash壳脚本)。这些很容易找到个别的现有解决方案,并可以结合做你想做的。 – 2014-11-03 06:22:25

+0

看起来好像你有一个答案,我想知道,如果你正在尝试这样做,而不是执行基于文件中一行输入的程序。文本文件是不是只是一个副作用? – Leon 2014-11-03 06:45:46

回答

1

您可以通过线这样使用循环

while read x 
    do 
    echo $x > inputFileInside.txt; 
    # do whatever you want 
    done < inputfile.txt 

读线,这可能HEP你循环,$ x是一行逐个读取,直到它到达文件

while read x 
    do 
    echo $x > $2; 
    ./myprogram paramater1 
     #your other command 
    done < $1; 

末保存上述文件像prog.sh任何名字,然后给执行权限,并与参数运行乌尔程序

chmod u+x prog.sh 
./prog.sh inputfile.txt inputFileInside.txt 

这里$ 1 inputfile.txt和$ 2是inputFileInside.txt

+0

非常感谢。其实我不知道如何像root $。/ myprogram parameter1 inputFileInside.txt和root $ sudo sh -c \“sync; echo 3>/proc/sys/vm/drop_caches \”那样运行程序。您是否也可以帮我一点这 – 2014-11-03 06:08:02

+1

另外我想让我的程序./myprogram在每个循环中终止它的运行。 – 2014-11-03 06:08:33

+0

inputFileInside.txt你想覆盖 – Hackaholic 2014-11-03 06:11:11

0
while read line; do 

    echo "$line" > inputFileInside.txt 

    ./myprogram paramater1 inputFileInside.txt \ 
    && sudo sh -c \"sync; echo 3 > /proc/sys/vm/drop_caches\" 

done < <(cat inputfile.txt) 

这将:

  • 输入文件 “inputfile.txt” 行由行
  • 各行将被分配到$行,因为它被读取
  • 将该行重新回写到“inputFileInside.txt”中,覆盖其中的任何先前信息
  • 运行“./myprogram ...”
  • 如果“./myprogram ...”成功,则只运行“sudo ...”
  • 转到下一行。

确保在行尾反斜杠(\)后面没有空格(空格)。

相关问题