Scripting String Parsing
I should write a shell script able to parse a comma
separated string.
An examle:
x,x,x,x,x
The problem is that the number of different 'x' is
not known so how can I get avery separated x string ?
Then I should write each x on a different line of
a text file.
Does a unique command exist or a script is necessary
?
You could parse it with awk.
echo "x,x,x,x,x" | awk -F"," '{ print NF }'
If the field count is unimportant but you just want to
deal with the values of each field, the tr command could be used to translate
commas to carriage returns.
cat comma.txt
File Server = pippo,pluto,paperino
File Server = bob,mary,bart,jim,buford
awk '{ print $NF }' comma.txt | tr "," "\012"
pippo
pluto
paperino
bob
mary
bart
jim
buford
Redirect stdout to append to a file if you want to save
the results. You can process many files in a for loop.
for file in *.log ; do
awk '{ print $NF }' $file | tr "," "\012" >> outfile
done
Looks homeworky to me. If instructor required "pure shell"
(no awk,sed ,tr ) and file contains
pippo,pluto,paperino
bob,mary,bart,jim,buford
you could submit:
Script < file
where Script is:
IFS=,
while read a
do
for f in $a
do
echo $f
done
done
for production, the above is the best way.
Have a Unix Problem
Do
you have a UNIX Question?
Unix Books :-
UNIX Programming,
Certification, System Administration, Performance Tuning Reference Books
Return to : - Unix
System Administration Hints and Tips
(c) www.gotothings.com All material on this site is Copyright.
Every effort is made to ensure the content integrity.
Information used on this site is at your own risk.
All product names are trademarks of their respective
companies.
The site www.gotothings.com is in no way affiliated with
or endorsed by any company listed at this site.
Any unauthorised copying or mirroring is prohibited.
|