How do I use variables in single quoted strings?

后端 未结 7 2092
既然无缘
既然无缘 2020-11-22 15:40

I am just wondering how I can echo a variable inside single quotes (I am using single quotes as the string has quotation marks in it).

     echo \'test text          


        
7条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 16:07

    You can do it this way:

    $ counter=1 eval echo `echo 'test text \
       "here_is_some_test_text_$counter" "output"' | \
       sed -s 's/\"/\\\\"/g'` > file
    
    cat file
    test text "here_is_some_test_text_1" "output"
    

    Explanation: Eval command will process a string as command, so after the correct amount of escaping it will produce the desired result.

    It says execute the following string as command:

    'echo test text \"here_is_some_test_text_$counter\" \"output\"'
    

    Command again in one line:

    counter=1 eval echo `echo 'test text "here_is_some_test_text_$counter" "output"' | sed -s 's/\"/\\\\"/g'` > file
    

提交回复
热议问题