Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk: warning: escape sequence `\]' treated as plain `]'

Tags:

awk

echo "A:\ B:\ C:\ D:\" | awk -F'[:\]' '{print $1}'

Output:

awk: warning: escape sequence `\]' treated as plain `]'

A

I am getting the above warning message, I have tried multiple options to escape the ] but that didn't resolve.

I want to use both the delimiters :\ and print exactly the alphabets A, B, C, D by printing $1, $2, $3, $4 respectively.

like image 388
user3834663 Avatar asked Sep 16 '14 11:09

user3834663


People also ask

How do you escape a backslash in awk?

In awk strings, backslash is used to introduce C-like escape sequences like \b for backspace, \n for newline, \123 for octal sequences... You need \\ for backslash itself.

How do you escape characters in awk?

One use of an escape sequence is to include a double-quote character in a string constant. Because a plain double quote ends the string, you must use ' \" ' to represent an actual double-quote character as a part of the string. For example: $ awk 'BEGIN { print "He said \"hi!\


2 Answers

I think this is what you're trying to do:

$ echo 'A:\ B:\ C:\ D:\' | awk -F':\\\\[[:space:]]*' '{print $2}'
B

Note that I added [[:space:]]* as I don't think you want leading spaces in the fields after $1.

String literals as used in your FS setting get parsed twice, once when the script is read and again when executed so escapes need to be doubled up (google it and/or read the awk man page or book). In this case on the first pass \\\\ gets converted to \\ and on the second pass \\ gets converted to \ which is what you want.

like image 114
Ed Morton Avatar answered Oct 02 '22 22:10

Ed Morton


This is also wrong:

echo "A:\ B:\ C:\ D:\"

You are escaping the " and it breaks the input, you need to remove it or use single quote.

awk does not like a single \ within field separator, so try:

echo 'A:\ B:\ C:\ D:\' | awk -F":|\\" '{print $1}'
A

Or you can escape it (single quote):

echo 'A:\ B:\ C:\ D:\' | awk -F'[:\\\\]' '{print $1}'
A

Or even more escaping (double quote):

echo 'A:\ B:\ C:\ D:\' | awk -F"[:\\\\\\\]" '{print $1}'
A
like image 44
Jotne Avatar answered Oct 02 '22 23:10

Jotne