system
January 27, 2011, 10:28am
1
Hi,
I want to count the number of occurences of a character in a string variable ($str). The character is stored in a another variable ($sepchr). I am using tr as :
$count = ($str =~ tr/$sepchr//);
This did not work. I found in another thread about using eval. I used eval as :
$count = ($str =~ eval "tr/$sepchr//");
But this too did not work.
Please advise.
Thanks
I would use global matching for that:
# perl -le'
$s = "ababbaa";
$c = shift;
$n = () = $s =~ /$c/g;
print $n;
' a
4
# perl -le'
$s = "ababbaa";
$c = shift;
$n = () = $s =~ /$c/g;
print $n;
' b
3
xerox
February 22, 2011, 7:42am
3
wat does 015 mean in this command?
tr -d \\015 < file
$ man ascii | grep 015
Reformatting page. Please Wait... done
010 BS 011 HT 012 NL 013 VT 014 NP 015 CR 016 SO 117 SI
CR - Carriage Return.
1 Like
You could use the s/// operator as well, at the expense of modifying the original string -
$
$
$ perl -le '$str="ababbaa"; $sepchr="a"; $count = $str =~ s/$sepchr//g; print $count'
4
$
$
$ perl -le '$str="ababbaa"; $sepchr="b"; $count = $str =~ s/$sepchr//g; print $count'
3
$
$
tyler_durden
1 Like
xerox
February 22, 2011, 11:03pm
6
many thanks for the previous post....
i want to remove ^M(ctrl-v ctrl-m) from a file through script using sed command...can u suggest sumthin.....
---------- Post updated at 09:33 AM ---------- Previous update was at 09:32 AM ----------
many thanks for the previous post....
i want to remove ^M(ctrl-v ctrl-m) from a file through script using sed command in shell script...can u suggest sumthin.....
tene
February 23, 2011, 12:37am
7
sed 's/^M//g' yourfile > newfile
xerox
February 23, 2011, 2:11am
8
i tried it...its not working through script.....the output file still contains ^M
---------- Post updated at 12:41 PM ---------- Previous update was at 12:36 PM ----------
i tried in thru script...but its not working....
Could this help you ?
perl -i -pe 's/\r//g' inputfile
1 Like
xerox
February 23, 2011, 4:03am
10
i need it in shell script....
Try:
sed 's/type <Ctrl-V><ENTER> here//g' yourfile > newfile
xerox
February 23, 2011, 4:51am
12
its not working....
---------- Post updated at 03:21 PM ---------- Previous update was at 03:20 PM ----------
testt.sh:
sed 's/^@//g' newfile > chk
It did not work because you typed:
^@
despite being told to type:
<Ctrl-V><Enter>
No wonder it did not work.
tyler_durden
Try "\r" alternatively; looks like it works with GNU sed -
$
$ # display the contents of file "f1"
$ cat f1
1
12
123
$
$ # check the octal dump of "f1" to see the "\r" characters
$ od -bc f1
0000000 061 015 012 061 062 015 012 061 062 063 015 012
1 \r \n 1 2 \r \n 1 2 3 \r \n
0000014
$
$ # the shell script to remove "\r" characters
$ cat f1.sh
sed 's/\r//g' f1 > f1.new
$
$ # run the shell script
$ . f1.sh
$
$ # check the new file now
$ cat f1.new
1
12
123
$
$ od -bc f1.new
0000000 061 012 061 062 012 061 062 063 012
1 \n 1 2 \n 1 2 3 \n
0000011
$
$
1 Like