Thursday, April 7, 2022

[SOLVED] Printing a certain number of lines from variable in bash

Issue

From a file:

Hello
World
Foo
Bar

You can print a certain number of lines with: awk 'NR<=2' file

Hello
World

How would you print the first two lines of a variable?

x="$(cat file)"

Solution

In case you are not looking to solve it specifically with awk, a very easy fix can be using head.

$ read -r -d '' VAR << EOM
This is line 1.
This is line 2.
Line 3.
Line 4.
EOM

$ echo "$VAR"
This is line 1.
This is line 2.
Line 3.
Line 4.

$ echo "$VAR"|head -2
This is line 1.
This is line 2.


Answered By - Nahid Iftekhar
Answer Checked By - Willingham (WPSolving Volunteer)