Note that there are some explanatory texts on larger screens.

plurals
  1. POfetch nth line of a text file using non-interactive shell script
    text
    copied!<p>i need to fetch the nth line of a txt file using shell script.</p> <p>my text file is like</p> <pre><code>abc xyz </code></pre> <p>i need to fetch the 2nd line and store it in a variable</p> <p>i've tried all combinations using commands like : </p> <ol> <li>sed </li> <li>awk </li> <li>head </li> <li>tail</li> <li>cat</li> </ol> <p>... etc</p> <p>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.</p> <p>I expect, it has something to do with the non-interactive shell.</p> <p>Please help</p> <p>PS : using read command i'm able to store the first line in a variable.</p> <pre><code>read -r i&lt;edit.txt </code></pre> <p>here , "i" is the variable and edit.txt is my txt file.</p> <p>but i cant figure out, how to get the second line.</p> <p>thanks in advance</p> <p>edit : ALso the script exits, when i use these "non-working" commands, And none of the remaining commands is executed.</p> <p>already tried commands : </p> <pre><code>i=`awk 'N==2' edit.txt` i=$(tail -n 1 edit.txt) i=$(cat edit.txt | awk 'N==2') i=$(grep "x" edit.txt) </code></pre> <p>java code:</p> <pre><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(); } } </code></pre> <p>myscript.sh</p> <pre><code>read -r i&lt;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 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload