bash Perl 脚本逐行读取文件并在每行上运行命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6406343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 00:12:31  来源:igfitidea点击:

Perl Script to Read File Line By Line and Run Command on Each Line

perlbashicu

提问by Nathan

I found this perl script herewhich seems will work for my purposes. It opens a Unicode text file and reads each line so that a command can be run. But I cannot figure out how to run a certain ICU command on each line. Can someone help me out? The error I get is (largefile is the script name): syntax error at ./largefile line 11, near "/ ." Search pattern not terminated at ./largefile line 11.

我在这里找到了这个 perl 脚本它似乎对我有用。它打开一个 Unicode 文本文件并读取每一行,以便可以运行命令。但我无法弄清楚如何在每一行上运行某个 ICU 命令。有人可以帮我吗?我得到的错误是(largefile 是脚本名称):语法错误在 ./largefile 第 11 行,靠近“/”。搜索模式未在 ./largefile 第 11 行终止。

#!/usr/bin/perl

use strict;
use warnings;

my $file = 'test.txt';
open my $info, $file or die "Could not open $file: $!";

while( my $line = <$info>)  {      
do
LD_LIBRARY_PATH=icu/source/lib/ ./a.out "$line" >> newtext.txt
done
}

close $info;

Basically I want to open a large text file and run the command (which normally runs from the command line...I think how I call this in the perl script is the problem, but I don't know how to fix it) "LD_LIBRARY_PATH=icu/source/lib/ ./a.out "$line" >> newtext.txt" on each line so that "newtext.txt" is then populated with all the lines after they have been processed by the script. The ICU part is breaking words for Khmer.

基本上我想打开一个大文本文件并运行命令(通常从命令行运行......我认为我如何在 perl 脚本中调用它是问题,但我不知道如何修复它)“ LD_LIBRARY_PATH=icu/source/lib/ ./a.out "$line" >> newtext.txt" 在每一行上,以便“newtext.txt”在所有行被脚本处理后填充。ICU 部分正在为高棉语断言。

Any help would be much appreciated! I'm not much of a programmer... Thanks!

任何帮助将非常感激!我不是一个程序员......谢谢!

采纳答案by Adithya Surampudi

For executing terminal commands, the command needs to be in system(), hence change to

为了执行终端命令,命令需要在 system() 中,因此更改为

system("LD_LIBRARY_PATH=icu/source/lib/ ./a.out $line >> newtext.txt");

回答by j.w.r

Have you tried backticks:

您是否尝试过反引号:

while (my $line = <$info>) {
  `LD_LIBRARY_PATH=icu/source/lib/ ./a.out "$line" >> newtext.txt`
  last if $. == 2;
}