Originally Posted by George2
Why the following command will split by space or tab or \n?
tr ' \t' '\n\n'
read two lists of characters, and then goes through all the input and translates any instance of any character in the first list with the corresponding character in the second list.
Consider these examples:
% echo "This is my input string" | tr 'itp' 'IT_'
tr replaces all instances of 'i' with 'I', all instance of 't' with 'T' and all instance of 'p' with '_'. Thus the output is:
ThIs Is my In_uT sTrIng
You can have as many characters as you like in the two parameters. You can also use ranges of characters, so long as the ranges match length:
% echo "This is my input string" | tr '[a-j]' '[0-9]'
T78s 8s my 8nput str8n6
% echo "This is my input string" | tr 'abcdefghik' 'xxxxxxxxxx'
Txxs xs my xnput strxnx
A space is represented simply with a space character. Tabs are represented with '\t', new lines with '\n'. Hence the behaviour of the original tr command:
% echo "This is my input string" | tr ' \t' '\n\n'
Once the output is one word per line like that, you can use grep -c to count all lines which match the pattern. Since you want to match the whole word, you can add ^ and $ around the pattern. Alternatively you could use the -x option to grep to match the whole line, so a slight different version of the originally suggested command is like this:
tr ' \t' '\n\n' < input_file |grep -cx 'foo'
I made a small mistake in the original command, thinking tr takes an option third parameter being the name of an input file. This is not the case, so I used input re-direction with the < operator.