School of Physics, Mathematics, and Computing 
Not logged in (login)

This forum is provided to promote discussion amongst students enrolled in CITS4407 Open Source Tools and Scripting.

Before posting a question here, you might want to search the forum for previous posts asking the same question.
And please keep the discussion civil (as required by UWA's Computer Use Policy, #9).

RSS cloud
Jump to:

awk command deleting blank spaces

1 of 108 articles shown, currently no other people reading this forum.
From: Arran S.
Date: Mon 12th Apr 2021, 10:30am

Hi Muhammad.

The right hand side of this assignment statement just needs to go in double quotes. In 
general, to get Bash to preserve spaces in something, you need to put it in double quotes.

So this will work:

$ line2="$(awk 'NR==2 {print; exit}' < example1)"

or instead of awk you could use head and tail (though awk is likely to be faster):

$ line2="$(tail -n +2 < example1 | head -n 1)"

If you want to double-check exactly what's in the string and whether it contain spaces, some 
code like this can be useful:

$ printf '%s\n' "---------------------------------------" && \
  printf "Line2 is: '%s'\n" "$line2"

The "printf" command is useful for printing strings that have special characters in them - 
spaces, braces, asterisks and so on. The textbook has a section on it in chapter 21,  
"Formatting Output", if you want more information.

I hope that helps.



"Muhammad Arslan" <22*7*6*[email protected]*u*e*t*u*a*e*u*a*> wrote:

> suppose I have the file (example1) which contains the following:
> asdfghjklasdfghjklasdfghjkl
>                           l
> ajhfjjksanvkjasnvkjnvkjsank 
> I am trying to use awk to put the second line of the file into a variable. I am doing 
> this by:
> line2=$(awk 'NR==2 {print; exit}' < example1)
> however when I try to do:
> echo $line2
> the outcome is: 
> l
> is there a way I can keep the blanks lines as well thanks

Related articles

awk command deleting blank spaces (both) RSS
├─ original   Sun 11th Apr 2021, 2:57pm, Muhammad A.
└─ THIS   Mon 12th Apr 2021, 10:30am, Arran S.
This Page

Program written by: [email protected]
Feedback welcome
Last modified:  6:26am Aug 12 2021