0

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

我的文本文件就像

abc
xyz

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

我已经使用以下命令尝试了所有组合:

  1. sed
  2. awk
  3. 尾巴

... ETC

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

我希望,它与非交互式外壳有关。

请帮忙

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

read -r i<edit.txt

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

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

提前致谢

编辑:当我使用这些“非工作”命令时,脚本也会退出,并且没有执行剩余的命令。

已经尝试过的命令:

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

爪哇代码:

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();  }
}

脚本文件

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
4

2 回答 2

3

从文件中打印第 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();  }

外壳脚本:

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

echo -n "file path is: "
sed '2q;d' "$f"
于 2013-12-19T07:02:47.247 回答
0

尝试这个:

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

其中 X 是您的行号:

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

对于第 4 行。

于 2013-12-19T07:19:00.943 回答