Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the field separator of awk to newline

Tags:

awk

The -F option lets you specify the field separator for awk, but using '\n' as the line separator doesn't work, that is, it doesn't make $1 the first line of the input, $2 the second line, and so on.

I suspect that this is because awk looks for the field separator within each line. Is there a way to get around this with awk, or some other Linux command? Basically, I want to separate my input by newline characters and put them into an Excel file.

I'm still warming up to Linux and shell scripts, which is the reason for my lack of creativity with this problem.

Thank you!

like image 931
user3565552 Avatar asked Jun 13 '17 00:06

user3565552


People also ask

How do you change the awk separator?

Just put your desired field separator with the -F option in the AWK command and the column number you want to print segregated as per your mentioned field separator.

How do I add a new line in awk?

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

How do you use a field separator in awk?

The variable FS is used to set the input field separator. In awk , space and tab act as default field separators. The corresponding field value can be accessed through $1 , $2 , $3 ... and so on. -F - command-line option for setting input field separator.

What is the default field separator in awk?

The default value of the field separator FS is a string containing a single space, " " . If awk interpreted this value in the usual way, each space character would separate fields, so two spaces in a row would make an empty field between them.


1 Answers

You may require to overwrite the input record separator (RS), which default is newline.

See my example below,

$ cat test.txt
a
b
c
d

$ awk 'BEGIN{ RS = "" ; FS = "\n" }{print $1,$2,$3,$4}' test.txt
a b c d
like image 192
CWLiu Avatar answered Sep 23 '22 10:09

CWLiu