2

I read code which is trying Change single blank lines to double blank lines using awk. But it did not works for me.

awk ~NF<2{printf\~\n\~}{print}~ <contour.dat >contour1.dat

After I read the tutorial of awk, like NF, Escape Sequences, I still don't have any clue about this code. This is the first time that I use awk.

I run it in bash. It gives me:

-bash: 2{printf~n~}{print}~: No such file or directory

What's the correct code should be?

Thank you in advance.

My Env

GNU bash, version 3.2.51(1)-release (x86_64-apple-darwin13) Copyright (C) 2007 Free Software Foundation, Inc.

awk version 20070501

1
  • 2
    What do you expect to happen for 2 or more consecutive empty lines in the source?
    – Philippos
    May 11, 2017 at 8:56

1 Answer 1

4
awk ~NF<2{printf\~\n\~}{print}~ 

I think those tildes should be double-quotes if you run the command in the shell:

awk "NF<2{printf\"\n\"}{print}"

The error you get is because the shell sees the < as a redirection operator, and takes the following part as a file name.

Or better yet, put the awk script in single-quotes so you don't need to escape the quotes within it:

awk 'NF<2{printf"\n"}{print}'

This would print an extra newline just before any line with less than two fields. But that's not the same as an empty line, lines with just a single word would still get the extra empty line added.

Maybe check if there are exactly zero fields:

awk 'NF == 0 {printf "\n"} {print}'

or if the line is totally empty:

awk '$0 == "" {printf "\n"} {print}'

But since the default action is to print $0 and an empty string is falsy, and printf "\n" is pretty much the same as print with an empty line, that could be condensed to just:

awk '!$0; 1'
10
  • I think those tildes should be double-quotes - In the original page awk is run from within gnuplot, not in a shell. May 11, 2017 at 8:57
  • @SatoKatsura, FWIW, I can't find any reference to gnuplot taking the ~ specially, and on a simple test, !echo ~foo bar~ within gnuplot prints tildes, so I'd guess that's just a formatting bug in the source.
    – ilkkachu
    May 11, 2017 at 9:10
  • It's a control code in enhanced mode... May 11, 2017 at 9:17
  • No, but it explains how ~ got there: the page was likely prepared for PostScript (where the awk line was emphasized), then somebody thought it would be cool to render it as HTML and put it on the intertubes. May 11, 2017 at 9:24
  • No chat-capable browser here, sorry... May 11, 2017 at 9:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .