Search code examples
javabashshnon-interactive

fetch nth line of a text file using non-interactive shell script


i need to fetch the nth line of a txt file using shell script.

my text file is like

abc
xyz

i need to fetch the 2nd line and store it in a variable

i've tried all combinations using commands like :

  1. sed
  2. awk
  3. head
  4. tail
  5. cat

... etc

problem is, when the script is called from the terminal, all these commands work fine. but when i call the same shell script, from my java file, these commands do not work.

I expect, it has something to do with the non-interactive shell.

Please help

PS : using read command i'm able to store the first line in a variable.

read -r i<edit.txt

here , "i" is the variable and edit.txt is my txt file.

but i cant figure out, how to get the second line.

thanks in advance

edit : ALso the script exits, when i use these "non-working" commands, And none of the remaining commands is executed.

already tried commands :

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 code:

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

Solution

  • An efficient way to print nth line from a file (especially suited for large files):

    sed '2q;d' file
    

    This sed command quits just after printing 2nd line rather than reading file till the end.

    To store this in a variable:

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

    OR using a variable for line #:

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

    UPDATE:

    Java Code:

    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 script:

    f=$(dirname $0)/edit.txt
    read -r i < "$f"
    echo "session is: $i"
    
    echo -n "file path is: "
    sed '2q;d' "$f"