2

I wrote the following code, where:

  • $1 = Input .csv file
  • $2 = list of strings to be searched in $1
  • $3 = list of different strings to be searched in $2
while read str1
do
    while read str2
    do
     grep $str1 $1 | grep $str2 | cut -d "," -f 6 > ${str1}_${str2}.txt
    done < $3
done < $2

It basically does what I want it to do (search for two different strings from separate input files, extract field 6 of lines that contain both strings and write the content of field 6 into a result file). However, of course, result files are created for all possible combinations of strings from $2 and $3, even if they are empty. Is there a way to prevent the creation of empty files in general or do I have to remove them at the end?

3
  • 2
    An improvement in many ways would be to rewrite this as an Awk script which processes each input file just once. Then writing only files for which you have a result is easily and naturally expressed. Commented Feb 4, 2018 at 18:15
  • 2
    As an aside, you need quotes basically everywhere. Try shellcheck.net for detailed diagnostics. Commented Feb 4, 2018 at 18:17
  • 1
    I wouldn't be surprised if given details of the input formats (ie. if the items being matched from a given input are all in a single column) much of the work we're currently calling two greps per line over could be modified to a single-pass join piped to a loop (in awk, if we cared about performance) that splits results out into separate files. But details matter, and they aren't adequately given here. Commented Feb 4, 2018 at 19:00

1 Answer 1

2

You can capture program output with $(...):

res=$(grep "$str1" "$1" | grep "$str2" | cut -d "," -f 6)

and with -n test, if a String is empty:

if [[ -n $res ]]; then echo "$res" > "${str1}_${str2}.txt" ; fi
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.