Use a variable in a sed command

后端 未结 6 1353
梦谈多话
梦谈多话 2020-12-09 03:15

I can\'t seem to use a variable in a sed command, for example:

sed \"24s/.*/\"$ct_tname\"/\" file1.sas > file2.sas

I want $ct_tnam

相关标签:
6条回答
  • 2020-12-09 03:47

    The problem is that when $ct_fname is substituted, sed sees extra / separators, so

    sed "24s/.*/"$ct_tname"/" file1.sas > file2.sas
    

    becomes

    sed "24s/.*/"%let outputfile=/user/ct_ARGUMENT1.csv;"/" file1.sas > file2.sas
    

    and you'll get a sed error because there are 5 / instead of the expected 3.

    Instead, change your sed separators to an unused character like | or :, and either single or double quotes will work just fine:

    sed '24s|.*|'$ct_tname'|' file1.sas > file2.sas
    sed "24s|.*|"$ct_tname"|" file1.sas > file2.sas
    
    0 讨论(0)
  • 2020-12-09 03:48

    you need to use double quotes (") instead of single quotes ('). single quotes pass their content literally, without translating variables (expansion).

    try

    sed "24s/.*/\"$ct_tname\"/" file1.sas > file2.sas
    

    btw, if you're going to be editing a file (that is if file2.sas is a temporary file), you should be using ed instead.

    0 讨论(0)
  • 2020-12-09 03:48

    You need to use double (") quotes, with single (') quotes the value of the variable doesn't get replaced. Since you have double quotes in your replacement text, you need to escape them:

    sed "24s/.*/\"$ct_tname\"/" file1.sas > file2.sas
    
    0 讨论(0)
  • 2020-12-09 03:52

    In my case, i just remplaced single quotes by the double ones:

    for a in $(cat ext.cnf); do sed -n "/$a$/p" file1 >> file2; done
    

    For now, it's working well...

    0 讨论(0)
  • 2020-12-09 03:53

    Other answers focus on the use of escaped double quotes in their examples. Note that this is not always what you want :

    $ FOO="auie"; echo foo123bar|sed "s/123/\"$FOO\"/"
    foo"auie"bar
    $ FOO="auie"; echo foo123bar|sed "s/123/$FOO/"
    fooauiebar
    $ FOO="auie"; echo fooauiebar|sed "s/\"$FOO\"/123/"
    fooauiebar
    $ FOO="auie"; echo fooauiebar|sed "s/$FOO/123/"
    foo123bar
    
    0 讨论(0)
  • 2020-12-09 03:59

    Shell variables are not expanded inside single quotes. Try this instead:

    sed "24s/.*/\"$ct_tname\"/" file1.sas > file2.sas
    
    0 讨论(0)
提交回复
热议问题