dhuma
asked on
grep and write to file from Shell script
OS: Linux
Type: Shell Script
I have a CSV file in the following format.
'112'|1|'1480196'|15||'A'
'112'|1|'1481645'|15||'A'
'145'|1|'1492362'|15||'A'
'145'|1|'15103891'|15||'A'
'157'|1|'1536122'|15||'A'
'157'|1|'1537942'|15||'A'
'168'|1|'1587454'|15||'A'
'168'|1|'1596169'|15||'A'
From the above file, I would like to grep the rows with first column '145' and write them to a different file, can someone give me a script to do that.
Type: Shell Script
I have a CSV file in the following format.
'112'|1|'1480196'|15||'A'
'112'|1|'1481645'|15||'A'
'145'|1|'1492362'|15||'A'
'145'|1|'15103891'|15||'A'
'157'|1|'1536122'|15||'A'
'157'|1|'1537942'|15||'A'
'168'|1|'1587454'|15||'A'
'168'|1|'1596169'|15||'A'
From the above file, I would like to grep the rows with first column '145' and write them to a different file, can someone give me a script to do that.
ASKER
Thanks for quick response, is it possible to also print the count of records in the new file.
example: I want to print the number of rows copied to new file as a header record
therefore, the new file will look like this
Header 2 rows
'145'|1|'1492362'|15||'A'
'145'|1|'15103891'|15||'A'
example: I want to print the number of rows copied to new file as a header record
therefore, the new file will look like this
Header 2 rows
'145'|1|'1492362'|15||'A'
'145'|1|'15103891'|15||'A'
This will require a script ;-) like this:
#!/bin/bash
grep "^'145'" $1 >$2.$$
echo Header $( wc -l $2.$$ ) rows > $2
cat $2.$$ >> $2
rm $2.$$
call the script like
filterscript.sh source.csv destination.txt
#!/bin/bash
grep "^'145'" $1 >$2.$$
echo Header $( wc -l $2.$$ ) rows > $2
cat $2.$$ >> $2
rm $2.$$
call the script like
filterscript.sh source.csv destination.txt
ASKER
thanks, its working however it is printing the header like this
if there are 1349 row, then I am seeing this in the header
1349 camd.csv.4912 rows.
Looks like the wc -l command is also printing the file name in addition to the word count. can you trim that and I will accept the solution.
thanks
if there are 1349 row, then I am seeing this in the header
1349 camd.csv.4912 rows.
Looks like the wc -l command is also printing the file name in addition to the word count. can you trim that and I will accept the solution.
thanks
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
hernst42.
No need for the UUOC ;-)
wc -l <$2.$$
No need for the UUOC ;-)
wc -l <$2.$$
An alternate script is:
#!/bin/bash
(echo Header $(grep -c "^145" $1) rows; grep "^145" $1 ) >$2
#!/bin/bash
(echo Header $(grep -c "^145" $1) rows; grep "^145" $1 ) >$2
grep "^'145'" yourfile.csv >newfile.csv