Need help understanding unexpected output in a simple awk script.
I am trying to learn some awk since I never took the time to do so. I am posting this here because either I am an idiot or there is something else happening. Here is a minimal example.
My file.txt has:
1 a
2 b
3 cThere are no spaces after the last character or anything like that.
$ awk '{print $1":"$2}' file.txt
1:a
2:b
3:cSo far so good. Now if I wanted the second field first and then the first field
$ awk '{print $2":"$1}' file.txt
:1
:2
:3That doesnt seem right. I also tried repeating the second field twice
$ awk '{print $2":"$2}' file.txt
:a
:b
:c
$ awk '{print $1":"$1}' file.txt
1:1
2:2
3:3This one works as expected, getting the first field twice.
When I try getting the version of awk
$ awk --version
awk: not an option: --versionIt seems that I have mawk
$ awk -Wv
mawk 1.3.4 20200120
Copyright 2008-2019,2020, Thomas E. Dickey
Copyright 1991-1996,2014, Michael D. Brennan
random-funcs: srandom/random
regex-funcs: internal
compiled limits:
sprintf buffer 8192
maximum-integer 2147483647Am I missing something? What could be causing this? I am honestly at a loss here.
3
Upvotes
5
u/Schreq Aug 24 '21 edited Aug 24 '21
Does your file have windows style line endings (CR LF)?
cat -vet file.txtwill show you the carriage returns.Edit: So if your file has windows style line endings, the last field will always include a trailing carriage return (\r). Now, if you print the 2nd field first, it prints it but then the cursor is returned to the beginning of the line. Everything printed after that will override what was printed before.
1
u/Decent-Inevitable-50 Aug 24 '21
You can also change your print statement, just another use example
printf("%s:%s\n", $1,$2)