Passing two argument variables in grep while ignoring whitespace

Viewed 34

I'm trying to write a shell script that takes a parameter to search column 12 of a given csv file for a matching pattern, and then search for a pattern match in column 18 as another argument, both of which being strings that may or may not include a space. However what I've tried so far only takes the second argument up until whitespace, then begins thinking it is a nonexistent command. My code appears as such:

#!/bin/bash

grep -Po "^([^,]*,){11}$2*([^,]*){9}" "$1" | grep -E "^([^,]*,){17}$3*([^,]*){4}"

Wherein $2 is the pattern to be searched in column 12, $1 is the name of csv file, and $3 is the pattern to be searched in column 18. This also does not print any of the columns following column 12, when I would like to print the entire line (about 21-22 columns total). What am I doing incorrectly? (For context, fields are separated by commas in the test file being used). Thanks in advance

1 Answers

You have a minor error in your first regex:

"^([^,]*,){11}$2*([^,]*){9}" # your regex
"^([^,]*,){11}$2*(,[^,]*){9}" # correct regex

And there's a similar error in the 2nd regex.

I suggest you merge the regexes to make one command:

grep -Po "^([^,]*,){11}$2*(,[^,]*){5},$3(,[^,]*){4}" "$1"

The -o flag only prints the matching part, so you won't get any more output than what's matched by the first regex. Consider removing -o flag if you just want the whole line.

Related