0

awk -F '$' works well with single-dollar-sign-separated string (a$b$c for example), but when it comes to multiple dollar signs, awk does not work.

The expected output is: 1$23, I have tried the following combinations but in vain:

$ printf '1$23$$$456' | awk -F '$$$' '{print $1}'
1$23$$$456
$ printf '1$23$$$456' | awk -F '\$\$\$' '{print $1}'
1$23$$$456
$ printf '1$23$$$456' | awk -F '\\$\\$\\$' '{print $1}'
1$23$$$456
$ printf '1$23$$$456' | awk -F '$' '{print $1}'
1

I wonder if there is a way to split a string by a sequence of dollar signs using awk?

update

$ awk --version
awk version 20070501
$ echo $SHELL
/usr/local/bin/fish
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Weihang Jian
  • 7,826
  • 4
  • 44
  • 55

4 Answers4

3

The problem is due to fish quoting rules. The important difference is that fish, unlike Bash, allows escaping a single quote within a single quoted string, like so:

$ echo '\''
'

and, consequently, a literal backslash has to be escaped as well:

$ echo '\\'
\

So, to get what in Bash corresponds to \\, we have to use \\\\:

$ printf '1$23$$$456' | awk -F '\\\\$\\\\$\\\\$' '{print $1}'
1$23
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
2

awk and various shells have nasty behaviours with escaping characters with back-slashes. Various shells could have different behaviours and sometimes you really need to escape like crazy to make it work. The easiest is to use [$] for a single symbol. This always works for field separators as FS is a regular expression if it is more than one symbol.

$ awk -F '[$][$][$]' '{...}' file
kvantour
  • 25,269
  • 4
  • 47
  • 72
0

More \

#> printf '1$23$$$456' | awk -F '\\$\\$\\$' '{print $1}'
1$23
Artem Aliev
  • 1,362
  • 7
  • 12
  • Thanks for answering, unfortunately, It does not work with fish shell. I have updated the original post. – Weihang Jian Mar 19 '20 at 13:43
  • It is not shell but awk version problem: https://stackoverflow.com/questions/24332942/why-awk-script-does-not-work-on-mac-os-but-works-on-linux . I don't have that version to try – Artem Aliev Mar 19 '20 at 13:50
  • No, it's not an awk problem, I have the same awk version on macOS and it works fine with `'\\$'` in Bash. It's a shell quoting/escaping problem. If you look at the question you link, it actually ends with "the problem was not awk" ;) – Benjamin W. Mar 19 '20 at 14:12
0

Maybe not use awk if that's throwing you curves?

$: echo '1$23$$$456' | sed 's/$$$.*//'
1$23

Why farm it out to a subshell at all for somehting that's just string processing?

$: x='1$23$$$456'
$: echo "${x%%\$\$\$*}"
1$23
Paul Hodges
  • 13,382
  • 1
  • 17
  • 36