使用非交互式shell脚本获取文本文件的第n行

时间:2013-12-19 06:58:20

标签: java bash sh non-interactive

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

我的文字文件就像

abc
xyz

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

我已尝试使用以下命令进行所有组合:

  1. sed
  2. awk
  3. ...等

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

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

    请帮忙

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

    read -r i<edit.txt
    

    这里,&#34;我&#34;是变量,edit.txt是我的txt文件。

    但我无法弄清楚,如何获得第二行。

    提前致谢

    编辑: 当脚本退出时,我使用这些&#34;非工作&#34;命令,并且没有剩余的命令被执行。

    已尝试过命令:

    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
    

2 个答案:

答案 0 :(得分:2)

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

sed '2q;d' file

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

将其存储在变量中:

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"

答案 1 :(得分:0)

试试这个:

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

其中X是您的行号:

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

为第4行。