问题
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
??
回答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"
来源:https://stackoverflow.com/questions/38559634/write-to-a-file-filename-is-a-string-that-needs-to-be-manipulated-slightly