Operating System - HP-UX
1834395 Members
10293 Online
110066 Solutions
New Discussion

Re: what is the meaning of the script?

 
lin.chen
Frequent Advisor

what is the meaning of the script?

Dear,
customer has a script as following description.
#>aa=`tr '\0a' '?'
#echo $aa
4167798

Best regards,Louis
4 REPLIES 4
Dennis Handly
Acclaimed Contributor

Re: what is the meaning of the script?

I'm not sure why you have the ">" in "#>"?
It seems like there are problems. You only have octal escape sequences for tr(1). If it truly wants to translate a newline, it should use "\012".
So the script translates something into "?" in file salv_xxxt001.dmp, then uses grep to count the number of "?". That is assigned to aa and then it is echoed.
James R. Ferguson
Acclaimed Contributor

Re: what is the meaning of the script?

Hi:

I don't understand the convolutions here.

If the goal is simply to count newline (0x0a) characters, simply use 'wc -l file'.

The command you show shouldn't work to count lines since 'grep' is going to process *lines* and the left side of the pipe destroys the lines. That is, you are going to count the number of lines (one big long one!) with multiple "?" characters in it, thus returning a count of one.

If the object is to count some number of characters, this is fast:

# perl -nle '$n+=tr/x/x/;END{print $n}'

...substitute for 'x' the charcter you want counted.

Regards!

...JRF...
Dennis Handly
Acclaimed Contributor

Re: what is the meaning of the script?

>ME: You only have octal escape sequences for tr(1).

I took a look at this and it seems that it is doing is translating null chars to "?". The "a" is ignored since there is only one "?".
So it is counting the sum of null + "?" chars.
James R. Ferguson
Acclaimed Contributor

Re: what is the meaning of the script?

Hi (again):

> Dennis: I took a look at this and it seems that it is doing is translating null chars to "?". The "a" is ignored since there is only one "?".

Yes! I agree with you now! Consider:

# make a file with nulls and "a"s:

# perl -e 'print "\0a\n" for 1..10' > funnyfile
# cat -e funnyfile
^@a$
^@a$
^@a$
^@a$
^@a$
^@a$
^@a$
^@a$
^@a$
^@a$

# perl -nle '$n+=tr{\0}{\0};END{print $n}' funnyfile
10

# tr '\0a' '?' < funnyfile|grep -c '?'
10

...BUT this is much cleaner:

# tr '\0' '?' < funnyfile|grep -c '?'
10

...Observe that the shell 'tr' drops the "a" as Dennis noted, whereas Perl will not. Perl's 'tr' transliterates ALL occurrences of the characters found in the search list with the corresponding character in the replacement list!

# perl -nle '$n+=tr{\0a}{\0a};END{print $n}' funnyfile
20

Regards!

...JRF...