0

This is a string I want to manipulate and be part of a filename I want to write to:

$ echo "$val1"
"$29.95 Carryover Plan 1GB"

This is what I want the file name to be, (spaces repalaced with underscore and double quotes removed) and NAME_ added at start and _NAME added at end.

$ echo "NAME_"$val1"_NAME" | sed s/" "/_/g | sed s/'"'/''/g
NAME_$29.95_Carryover_Plan_1GB_NAME

And this is me trying to write test data to the file in question

$ a="NAME_"$val1"_NAME" | sed s/" "/_/g | sed s/'"'/''/g && echo "test123" > "$a"

But it does not come out as I want "$29.95_Carryover_Plan_1GB"

$ ls -lth
total 44M
-rw-r--r-- 1 kevin.smith mkpasswd    8 Jul 25 16:08 "$29.95_Carryover_Plan_1GB"

How can I write to the file and for the file name to be NAME_$29.95_Carryover_Plan_1GB_NAME??

Huy Nguyen
  • 2,025
  • 3
  • 25
  • 37
HattrickNZ
  • 4,373
  • 15
  • 54
  • 98

1 Answers1

1
a="NAME_"$val1"_NAME" | sed s/" "/_/g | sed s/'"'/''/g

doesn't do what I expect you wanted it to. You'll need to actually echo the variable:

a="$(echo "NAME_"$val1"_NAME" | sed s/" "/_/g | sed s/'"'/''/g)"

Or a bit nicer (IMO):

a="$(echo "NAME_${val1}_NAME" | sed 's/ /_/g;s/"//g')"

Or if you're running zsh rather than bash:

a="NAME_${${val1// /_}//\"/}_NAME"
viraptor
  • 33,322
  • 10
  • 107
  • 191
  • `$ a="NAME_${${val1// /_}//\"/}_NAME" -sh: NAME_${${val1// /_}//\"/}_NAME: bad substitution` that is a q i asked [here](http://stackoverflow.com/questions/38559463/how-to-replace-spaces-with-underscore-and-doublequotes-with-nothing-in-bash/38561193#38561193) and was told it could not be done. Can you explain why I am getting `bad substitution`? – HattrickNZ Jul 25 '16 at 22:36
  • 1
    I forgot to note this doesn't work in bash. Fixed now. – viraptor Jul 25 '16 at 23:37