Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print out a newline character in a string in Awk

Tags:

unix

awk

Tried googling everywhere and I couldn't find anything. I'm trying to figure this out...how would one print out the actual \n char at the end of a line so that in the output file it comes out:

stuff stuff stuff \n stuff stuff stuff \n stuff stuff stuff \n stuff stuff stuff \n

Any and all help is appreciated.

like image 374
Richard John Catalano Avatar asked Aug 17 '15 09:08

Richard John Catalano


People also ask

How do I print a newline in awk?

Append printf "\n" at the end of each awk action {} . printf "\n" will print a newline.

What is awk '{ print $1 }'?

If you notice awk 'print $1' prints first word of each line. If you use $3, it will print 3rd word of each line.

What does awk '( print $9 do?

awk '{print $9}' the last ls -l column including any spaces in the file name.

What does GSUB do in awk?

The gsub() function returns the number of substitutions made. If the variable to search and alter ( target ) is omitted, then the entire input record ( $0 ) is used. As in sub() , the characters ' & ' and ' \ ' are special, and the third argument must be assignable. If find is not found, index() returns zero.

How do I print text in awk?

To print a blank line, use print "" , where "" is the empty string. To print a fixed piece of text, use a string constant, such as "Don't Panic" , as one item. If you forget to use the double-quote characters, your text is taken as an awk expression, and you will probably get an error.


1 Answers

I believe that all you would have to do is escape the slash in \n in the following way: \\n.

Here is a simple example:

ll | awk '{ printf "%s\\n\n",$1 }'

This should print the permissions column for each file in the current directory and after each line of input, a literal newline character \n is inserted after which an actual newline is inserted.

The result should look something like this:

drwxrwxr-x.\n
-rw-rw-r--.\n
-rw-rw-r--.\n
-rwxrwxr-x.\n
-rwxrwxr-x.\n
drwxrwxr-x.\n
drwxrwxr-x.\n

As you can see, there is a literal \n at the end of each line.


If you don't want any "real" newline characters and have all of your output on one line, you can remove the second \n from the printf statement:

ll | awk '{ printf "%s\\n",$1 }'

This will give you output very similar to what you mentioned in your question with a literal \n appended to each input line:

\n-rwxrwxr-x.\ndrwxrwxr-x.\n-rw-rw-r--.\n-rwxrwxr-x.\ndrwxrwxr-x.\n-rw-rw-r--.\ndrwxrwxr-x.\n-rw-rw-r--.\n
like image 99
Lix Avatar answered Sep 21 '22 08:09

Lix