bash - Create variable by combining text + another variable -
long story short, i'm trying grep value contained in first column of text file using variable.
here's sample of script, grep command doesn't work:
for ii in `cat list.txt` grep '^$ii' >outfile.txt done
contents of list.txt :
123,"first product",description,20.456789 456,"second product",description,30.123456 789,"third product",description,40.123456
if perform grep '^123' list.txt
, produces correct output... first line of list.txt.
if try use variable (ie grep '^ii' list.txt
) "^ii command not found" error. tried combine text variable work:
var1= "'^"$ii"'"
but var1
variable contained carriage return after $ii
variable:
'^123 '
i've tried laundry list of things remove cr/lr (ie sed & awk), no avail. there has easier way perform grep command using variable. prefer stay grep command because works when performing manually.
you have things mixed in command grep '^ii' list.txt
. character ^
beginning of line , $
value of variable. when want grep 123 in variable ii @ beginning of line, use
ii="123" grep "^$ii" list.txt
(you should use double quotes here)
moment learning habits: continue in variable names in lowercase (well done) , use curly braces (don't harm , needed in other cases) :
ii="123" grep "^${ii}" list.txt
now both forgetting something: our grep
match 1234,"4-digit product",description,11.1111
. include ,
in grep:
ii="123" grep "^${ii}," list.txt
and how did "^ii command not found" error ? think used backquotes (old way nesting command, better echo "example: $(date)"
) , wrote
grep `^ii` list.txt # wrong !
Comments
Post a Comment