-2

How to tell awk not to parse a string in a variable assignment with -v option:

$ awk -v s='\n' 'BEGIN {print "[" s "]"}'
[
]

it does not parse in the following

$ echo '\n' | awk '{print "[" $0 "]"}'
[\n]
$ awk 'BEGIN {print "[" ARGV[1] "]"}' '\n'
[\n]
$ s='\n' awk 'BEGIN {print "[" ENVIRON["s"] "]"}'
[\n]

And parses in the following

$ awk 'BEGIN {s = "\n"; print index(s, "n"), index(s, "\n")}'
0 1
slitvinov
  • 5,693
  • 20
  • 31
  • 3
    didn't see that you already know about `ENVIRON` before answering.. `-v` will always be treated as a string, `ENVIRON` is usually used to prevent that.. there's no way to tell awk to not parse `-v` variables as far as I know – Sundeep Nov 02 '20 at 13:34
  • 1
    @Sundeep is correct, when you use `-v` you are **telling** awk to interpret escape sequences. If you don't want that then don't use `-v`, see https://stackoverflow.com/q/19075671/1745001 for the other ways to pass literal strings to awk. – Ed Morton Nov 02 '20 at 19:37
  • 2
    I’m voting to close this question because the OP just misunderstood how the code works. – Ed Morton Nov 02 '20 at 19:39
  • @EdMorton Which code? The awk or shell code in my examples? The code of one of the awk implementations? I doubt you can reliably infer the state of my knowledge. Even if you can how it is relevant to https://stackoverflow.com/help/on-topic ? – slitvinov Nov 03 '20 at 08:33
  • The awk code of course, see the first 2 comments under your question. I don't need to infer the state of your knowledge, you're using the construct incorrectly and asking why you're getting the result you're getting therefore, by your explicit statements, you misunderstood how it works. That's relevant because this is just a common language construct being used incorrectly with explanations of the behavior already covered in other Q&A here and easily found by a quick google search (e.g. see the first stackexchange answer from https://www.google.com/search?q=awk+"-v"+escape+sequence). – Ed Morton Nov 03 '20 at 15:03
  • @EdMorton How did you infer I expect something different from what I get? I want a different result but of course something must be changed. There is also no "why" in my question. – slitvinov Nov 03 '20 at 16:41
  • You're absolutely right, it is an excellent question. All the best. – Ed Morton Nov 03 '20 at 16:44

1 Answers1

1

Just add an extra backslash to escape the backslash:

$ awk -v s='\\n' 'BEGIN {print "[" s "]"}'
[\n]
August Karlstrom
  • 10,773
  • 7
  • 38
  • 60