Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

field count in a delimited string

Status
Not open for further replies.

patnim17

Programmer
Jun 19, 2005
111
US
Hi,
I have a String delimited by a pipes."|"
eg: yxs|yud|abc|def|ghi

I want to find the count of the fields, so in this case it should be 5.

How can I get it linux/unix?

pat
 
If you look up tutorials on AWK, you will find something like this:

#!/usr/bin/awk -f
BEGIN {
string="yxs|yud|abc|def|ghi";
n=split(string,array,"|");
print(n);
exit;
}



Business and Data Integrations
A Northern Virginia IT Service and Consulting Company
 
Why not simply:
Code:
awk -F "|" '{ print NF }' yourtext.txt
or
Code:
echo "abc|def|ghi|jkl|mno" | awk -F "|" '{ print NF }'
 
Just out of curiosity..I was also trying to write this one mentioned by "bdintegrations":

#!/usr/bin/awk -f
BEGIN {
string="yxs|yud|abc|def|ghi";
n=split(string,array,"|");
print(n);
exit;
}

How do I do this inside a shell script. I poened up test.sh and copied the above in it and it doesn't seem to be working.

pat
 
You would have to paste that in to a separate script file of its own, making sure that the #!/usr/bin/awk -f line was the first line.

To use it in an existing script you could do this:

Code:
awk 'BEGIN {
    string="yxs|yud|abc|def|ghi";
    n=split(string,array,"|");
    print(n);
    exit;
}'

Annihilannic.
 
Also simple i bash

Code:
#!/bin/bash

OLDIFS=$IFS
IFS='|'

Str="Tom|Andy|Jacob|Sid|Pat"

n=`echo $Str|wc -w`;

echo "N=$n";

IFS=$OLDIFS
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top