0

I'm using the following command:

grep -F "searchterm" source.csv >> output.csv

to search for matching terms in source.csv. Each line in the source file is like so:

value1,value2,value3|value4,value5

How do I insert only the fields value1,value2,value3 into the output file?

Cong Ma
  • 10,692
  • 3
  • 31
  • 47
CrusaderAD
  • 11
  • 4

3 Answers3

1

You can simply use awk which will go through line by line and then you apply the separator and get the part you would like to take from the string .

awk -F"|" '{print $1}' input.csv > output.csv

Rabea
  • 1,938
  • 17
  • 26
  • 2
    Use of `cat` is redundant here. – Sobrique Oct 09 '15 at 16:12
  • Perhaps a silly question, but how is this applied with the grep functionality? – CrusaderAD Oct 12 '15 at 15:50
  • Not a silly question at all, but `grep` mainly is a tool to check for occurrences of a string with a matching pattern, `awk` on the other side is built for text processing. I would check this link for the purpose of using grep. http://stackoverflow.com/questions/16317961/how-to-process-each-line-received-as-a-result-of-grep-command – Rabea Oct 12 '15 at 16:25
  • Ah ok. So I would be looking for something like this? grep -F "searchterm" filetosearch.txt | awk -F"|" '{print $1}' input.txt > output.txt – CrusaderAD Oct 12 '15 at 16:48
0

You can do it with a simple while read loop:

while read -r line; do echo ${line%|*}; done < file.csv >> newfile.csv

or in a subshell, so you truncate the newfile each time:

( while read -r line; do echo ${line%|*}; done < file.csv ) > newfile.csv

or with sed:

sed -e 's/[|].*$//' file.csv > newfile.csv
David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
0

This perl solution is similar to the awk solution:

perl -F'\|' -lane 'print $F[0]' input.csv > output.csv

The | field separator character needs to be escaped with a \

-a puts perl into autosplit mode, which populates the fields array F

Chris Koknat
  • 3,305
  • 2
  • 29
  • 30