使用循环从某个行号开始写入

使用循环从某个行号开始写入
echo -n "which names (lower case only)?"
read name

假设输入为:brmu ankr ista

我需要在文本文件中第 20 行之后写入特定行,wrt 用户输入,距离行首有一个空格,如下所示;

brmu_gps expt ftprnx
ankr_gps expt ftprnx
ista_gps expt ftprnx

答案1

使用 Perl:

<<<"$x" perl -i -pe 'if($.==21){foreach(split(" ",<STDIN>)){print"${_}_gps expt ftprnx\n"}}' file

Perl 脚本扩展:

if($. == 21) { # if the current line's number is 21
    foreach(split(" ", <STDIN>)) { # splits STDIN on spaces and returns the splitted elements as an array; for each member of the array
        print("${_}_gps expt ftprnx\n") # print the current element followed by `_gps expt ftprnx` and a newline character
    }
}
  • <<<"$x":从变量读取输入x
  • -iin perl:指定由“<>”构造处理的文件将被就地编辑。
  • -pin perl: 使 Perl 假设你的程序中存在以下循环,这使得它像 sed 一样迭代文件名参数:

           LINE:
             while (<>) {
                 ...             # your program goes here
             } continue {
                 print or die "-p destination: $!\n";
             }
    
  • -ein perl:可用于输入一行程序。
% cat file
line #1
line #2
line #3
line #4
line #5
line #6
line #7
line #8
line #9
line #10
line #11
line #12
line #13
line #14
line #15
line #16
line #17
line #18
line #19
line #20
line #21
line #22
line #23
line #24
line #25
% read x
brmu ankr ista
% <<<"$x" perl -i -pe 'if($.==21){foreach(split(" ",<STDIN>)){print"${_}_gps expt ftprnx\n"}}' file
% cat file
line #1
line #2
line #3
line #4
line #5
line #6
line #7
line #8
line #9
line #10
line #11
line #12
line #13
line #14
line #15
line #16
line #17
line #18
line #19
line #20
brmu_gps expt ftprnx
ankr_gps expt ftprnx
ista_gps expt ftprnx
line #21
line #22
line #23
line #24
line #25

相关内容