bash variable interpolation separate variables by a hyphen or underscore

不想你离开。 提交于 2019-11-27 05:39:16

By telling bash where the variable name ends.

"${filename}_$yesterday.CSV"

Several possibilities:

  • The most natural one: enclose your variable name in curly brackets (Ignacio Vazquez-Abrams's solution):

    echo "${filename}_$yesterday.CSV"
    
  • Since your separator is a rather special character, you may use a backslash (Sriharsha's Kallury's solution):

    echo "$filename\_$yesterday.CSV"
    
  • (Ab)use quotes:

    echo "$filename""_$yesterday.CSV"
    

    or

    echo "$filename"_"$yesterday.CSV"
    
  • Use an auxiliary variable for the separator:

    sep=_
    echo "$filename$sep$yesterday.CSV"
    
  • Use an auxiliary variable for the final string, and build it step by step:

    final=$filename
    final+=_$yesterday.CSV
    echo "$final"
    

    or in a longer fashion:

    final=$filename
    final+=_
    final+=$yesterday
    final+=.CSV
    echo "$final"
    
  • Use an auxiliary variable for the final string, and build it with printf:

    printf -v final "%s_%s.CSV" "$filename" "$yesterday"
    echo "$final"
    

(feel free to add other methods to this post).

You can use backslash to do that.

# filename=test
# yesterday=somedate
# echo $filename_$yesterday.csv
somedate.csv
# echo $filename\_$yesterday.csv
test_somedate.csv
#
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!