I'm trying to write a shell script that scans both columns 1 and 7 for user-specified values, with $3 being matched in 7th column and $2 being a year matched in first column (and $1 the filename). I can match the 7th col just fine, but keep receiving the error 'sed: -e expression #1, char 7: unknown command: `2' when attempting to add the variable to match in first column. I have to use sed instead of awk for this unfortunately. Here's what I have thus far:
sed -n "/"$2",[^,],[^,],[^,],[^,],[^,]*,"$3"/p" "$1"
what should I try to fix this? I'm quite a noobie so all help is welcome. Tried shellcheck but it hasn't helped. The script runs fine when scanning 7th column but adding the $2 aspect causes errors.
Edit: Sample invocation:
./script.sh filename "2015.2016" "South"
Sample file (with "..." being a column with text inside):
2021/2022,text,text,text,text,text,South,text,...,...
2021/2022,text,text,text,text,text,North,text,...,...
2015/2016,text,text,text,text,text,South,text,...,...
2014/2015,text,text,text,text,text,West,text,...,...
Intended output:
2015/2016,text,text,text,text,text,South,text,...,...
Edit: While I agree that it's indeed not the best tool for the job, I figured out how to accomplish this with sed after playing around a bit:
#!/bin/bash
year="$2"
name="$3"
sed -n '/^'"$year"',\([^,]*,\)\{5\}'"$name"'\(,.*\)\{0,\}$/p' "$1"
Dunno if I'll ever make use of it but maybe it will help someone else out. Note that the input needs a "." rather than "/" in order to yield accurate result.
sed
for this,awk
is easier for field-separated data, and if this is an actual csv file, then you really should use a dedicated csv parser since csv fields can contain newlines and comas.sed -n "/^$year,\([^,]*,\)\{5\}$name\(,.*\)\{0,\}$/p" "$1"
script.sh file '2.*' 'South'
orscript.sh '2020' 'S/N'
or any of many other strings. That's why the script in my answer that uses sed is necessarily more complicated than yours, to protect against any of that.