Open In App
Related Articles

Write a bash script to print a particular line from a file

Improve Article
Save Article
Like Article

Given a file, name file.txt, out task is to write a bash script which print particular line from a file.

Content of file.txt:


Syntax in Bash Script

  1. awk :
    $>awk '{if(NR==LINE_NUMBER) print $0}' file.txt
  2. sed :
    $>sed -n LINE_NUMBERp file.txt
  3. head :
    $>head -n LINE_NUMBER file.txt | tail -n + LINE_NUMBER
    Here LINE_NUMBER is, 
    which line number you want to print


    Print a line from single file

    To print 4th line from the file then we will run following commands. The output of following lines will be “articles”.

    1. awk :
      $>awk '{if(NR==4) print $0}' file.txt
    2. sed :
      $>sed -n 4p file.txt 
    3. head :
      $>head -n 4 file.txt | tail -n + 4

    Print a line from multiple files

    Suppose we have two files, file1.txt and file2.txt, We can use the above commands and print particular line from multiple files by ‘&’.

    1. awk:
      $>awk '{if(NR==4) print $0}' file1.txt & awk '{if(NR==4) print $0}' file2.txt
    2. sed:
      $>sed -n 4p file1.txt & sed -n 4p file2.txt
    3. head:
      $>head -n 4 file1.txt | tail -n + 4 & head -n 4 file2.txt | tail -n + 4

    If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

    Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

    Last Updated : 26 Sep, 2017
    Like Article
    Save Article
Similar Reads