Home > Net >  how to replace 2nd filed of line separated by comma with a value stored in variable
how to replace 2nd filed of line separated by comma with a value stored in variable

Time:11-30

i have a line as below and all fields separated by comma:

I want to replace 2nd filed which is 11:50:21.444 with a value stored in variable "b"

01-01-2022,11:50:21.444,1234543233443,0,0,0,0,1

I tried using sed cat abc.csv| sed 's/$2/$b/'

CodePudding user response:

Any time you find yourself talking about fields you should use awk rather than sed or grep since awk has a concept of fields while the others don't and awk can do literal string replacements while sed can't.

awk -v b="$b" 'BEGIN{FS=OFS=","} {$2=b; print}' abc.csv

CodePudding user response:

Variables are not expanded in single quotes.

Also, sed has no idea of columns.

sed 's/^\([^,]*\),\([^,]*\)/$1,'"$b"/ abc.csv
       ^  ~~~~~  ^  ~~~~~
       |     |   |    |
start of     | Comma  |
the string   |       No comma
          No comma   again

Note that it can break if $b contains any characters special to sed, e.g. /.

  • Related