【问题标题】:fetch nth line of a text file using non-interactive shell script使用非交互式 shell 脚本获取文本文件的第 n 行
【发布时间】:2013-12-19 06:58:19
【问题描述】:

我需要使用 shell 脚本获取一个 txt 文件的第 n 行。

我的文本文件是这样的

abc
xyz

我需要获取第二行并将其存储在变量中

我已经尝试了所有使用命令的组合,例如:

  1. sed
  2. awk
  3. 尾巴

...等

问题是,当从终端调用脚本时,所有这些命令都可以正常工作。 但是当我从我的 java 文件中调用相同的 shell 脚本时,这些命令不起作用。

我想,这与非交互式外壳有关。

请帮忙

PS:使用读取命令我可以将第一行存储在变量中。

read -r i<edit.txt

这里,“i”是变量,edit.txt是我的txt文件。

但我不知道如何获得第二行。

提前致谢

编辑: ALso 脚本退出,当我使用这些“非工作”命令时,其余命令均未执行。

已经尝试过的命令:

i=`awk 'N==2' edit.txt`
i=$(tail -n 1 edit.txt)
i=$(cat edit.txt | awk 'N==2')
i=$(grep "x" edit.txt)

java代码:

try
    {
        ProcessBuilder pb = new ProcessBuilder("./myScript.sh",someParam);

        pb.environment().put("PATH", "OtherPath");

        Process p = pb.start(); 

        InputStreamReader isr = new InputStreamReader(p.getInputStream());
        BufferedReader br = new BufferedReader(isr);

        String line ;
        while((line = br.readLine()) != null)
           System.out.println(line);

        int exitVal = p.waitFor();
    }catch(Exception e)
    {  e.printStackTrace();  }
}

myscript.sh

read -r i<edit.txt
echo "session is : "$i    #this prints abc, as required.

resFile=$(echo `sed -n '2p' edit.txt`)    #this ans other similar commands donot do anything. 
echo "file path is : "$resFile

【问题讨论】:

标签: java bash sh non-interactive


【解决方案1】:

从文件中打印第 n 行的有效方法(特别适合大文件):

sed '2q;d' file

此 sed 命令在打印第二行后退出,而不是读取文件直到最后。

要将其存储在变量中:

line=$(sed '2q;d' file)

或者为第 # 行使用变量:

n=2
line=$(sed $n'q;d' file)

更新:

Java 代码:

try {
    ProcessBuilder pb = new ProcessBuilder("/bin/bash", "/full/path/of/myScript.sh" );
    Process pr = pb.start(); 
    InputStreamReader isr = new InputStreamReader(pr.getInputStream());
    BufferedReader br = new BufferedReader(isr);
    String line;
    while((line = br.readLine()) != null)
        System.out.println(line);
    int exitVal = pr.waitFor();
    System.out.println("exitVal: " + exitVal);
} catch(Exception e) {  e.printStackTrace();  }

Shell 脚本:

f=$(dirname $0)/edit.txt
read -r i < "$f"
echo "session is: $i"

echo -n "file path is: "
sed '2q;d' "$f"

【讨论】:

  • 在终端中有效,但在 java 程序调用相同的脚本时无效
  • 添加了 myscript.sh
  • 我用我建议的 shell 脚本更新了我的答案。你现在可以试试吗?
  • 再次使用 Java 和 shell 脚本代码查看更新。这是经过全面测试的代码 btw
  • 先生,edit.txt 文件位于当前目录中。路径不能硬编码。
【解决方案2】:

试试这个:

tail -n+X file.txt | head -1

其中 X 是您的行号:

tail -n+4 file.txt | head -1

第 4 行。

【讨论】:

  • 也可以使用更短的版本:tail -2 file.txt | head -1 当然,您可以获取输出并将其存储在变量中: line=`tail -2 file.txt |头 -1`
  • 在终端中有效,但在 java 程序调用相同的脚本时无效
猜你喜欢
  • 1970-01-01
  • 2012-07-03
  • 1970-01-01
  • 2011-08-29
  • 2017-02-11
  • 2015-06-29
  • 1970-01-01
  • 2014-07-16
  • 2016-05-29
相关资源
最近更新 更多