bash - How to pass variables in sed commands

I am trying to pass this line of code through my script:
row=8
title="sometitle"
sed -i $rowi"$title" hi.csv

where row represents the row I want to insert something in a csv file and title represents the content I want to insert into that row. The problem is sed won't pass the $row. I can't just use the command sed -i 8i"sometitle" hi.csv because the row and title variables change since im passing this sed command in a forloop. Is there any way for me to pass variables in a sed command? thanks in advance guys!

2 Answers

  1. Loren- Reply

    2019-11-13

    I tested your command and I guess you have to point out to the shell what the variable is, so you will have to surround it with curly braces, like this:

    sed -i ${row}i"$title" hi.csv
    

    EDIT: Another attempt to avoid an error (see comments):

    sed "${row} i\
    > $title
    > " hi.csv
    
  2. Lori- Reply

    2019-11-13

    row=8
    title=="sometitle"
    sed "${row} i\\^J${title}" hi.csv > YourFinal.csv
    

    Tested under ksh/AIX (so sed doesn't have -i option) [^J is a new line obtain with CTRL+V+J]

Leave a Reply

Your email address will not be published. Required fields are marked *

You can use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>