Sunday, July 12, 2009

How do you concatenate a string from Grep and a string output in printf in a linux terminal environment?

For example:


I want the result from grep -c .... and the string from printf message to be saved into one file.


So I thought of doing grep -c with printf, but I don't think it can be pipelined... So are there any alternatives?

How do you concatenate a string from Grep and a string output in printf in a linux terminal environment?
Hi --





It is hard to tell just what you are trying to do, so let me take a guess. I am assuming you are using a BASH shell.





If you wanted to count the occurrences of a string of characters that appear in a number of files and format the output to a nice list that is written to a file, you might do something like this:





grep -c "th" *.tst | xargs printf "%15s\n\r" %26gt; mytest.txt





...which would search files matching the pattern %26lt;any-name%26gt;.tst and pipe the output to the formated print statement, redirecting it to a file named mytest.txt. Then you could cat the file mytest.txt and see a listing like this:





cat mytest.txt


..podcast.tst:4


.......test1.tst:2


.........test.tst:2


.........tst.tst:61





Note: these are not be correctly padded here because this is html.





Alternatively, maybe you are trying to get the output from grep and then add a message at the end. For example:





grep -c "th" *.tst %26gt; mytest1.txt; printf "%15s\n\r" **End** %26gt;%26gt; mytest1.txt





...which uses redirection to create a file containing the output from the grep command and ADDS a final line from the printf for ouput like;





cat mytest1.txt





podcast.tst:4


test1.tst:2


test.tst:2


tst.tst:61


..........**End**





Note: the last line is not correctly padded here because this is html.





FYI, there are a couple of great BASH resources available on the web you may be interested in:


1) http://tldp.org/LDP/abs/html/ ...BASH Scripting Guide


2) http://tldp.org/HOWTO/Bash-Prog-Intro-HO...


...a nifty HowTo Guide.





hth.





--Rich

garden flowers

No comments:

Post a Comment