I am trying to figure out why this does not work and of course how to address it, I have a long list of dates in a variable and would like to count the number of occurrences using grep, it seems like splitting a variable over new lines does not work as expected? Example,
$ list="2015-a 2015-b 2016-a" ; count=`echo $list | tr " " \\n | grep 2015 | wc -l` ; echo $count
1
$ list="2015-a,2015-b,2016-a" ; count=`echo $list | tr , \\n | grep 2015 | wc -l` ; echo $count
1
$ list="2015-a,2015-b,2016-a" ; count=`echo $list | sed s/,/\\n/g | grep 2015 | wc -l` ; echo $count
1
Any ideas?
The problem is with the way backticks interpret \\\\
:
Backslashes () inside backticks are handled in a non-obvious manner:
$ echo "`echo \\\\a`" "$(echo \\\\a)" a \\a $ echo "`echo \\\\\\\\a`" "$(echo \\\\\\\\a)" \\a \\\\a # Note that this is true for *single quotes* too! $ foo=`echo '\\\\'`; bar=$(echo '\\\\'); echo "foo is $foo, bar is $bar" foo is \\, bar is \\\\
So instead of saying:
$ echo "`echo $list | tr " " \\n`"
2015-an2015-bn2016-a
You have to say:
$ echo "`echo $list | tr " " \\\\n`"
2015-a
2015-b
2016-a
Even though it is best to use $()
because backticks are deprecated:
$ echo "$(echo $list | tr " " '\n')"
2015-a
2015-b
2016-a
If you still want to use backticks, the cleanest solution is to use " "
as a wrapper instead of escaping with such a \\\\\\\\
:
$ echo "`echo $list | tr " " "\n"`"
2015-a
2015-b
2016-a
All of this can be read in Why is $(...) preferred over ...
(backticks)? .
All in all, if you just want to count how many words contain 2015
you may consider using grep -o
as suggested in the comments or maybe something more robust like this awk
:
awk '{for (i=1;i<=NF;i++) if ($i~2015) count++; print count}'
See some examples:
$ awk '{for (i=1;i<=NF;i++) if ($i~2015) s++; print s}' <<< "2015-a 2015-b 2016-a" 2
$ awk '{for (i=1;i<=NF;i++) if ($i~2015) s++; print s}' <<< "2015-a 2015-b 2016-a 20152015-c"
3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.