写入文件+文件名是需要稍作操作的字符串 [英] Write to a file + filename is a string that needs to be manipulated slightly
问题描述
这是我要操作的字符串,并且是我要写入的文件名的一部分:
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"
这就是我想要的文件名(用下划线和双引号删除的空格),并在开始时添加了NAME_
,并在末尾添加了_NAME
.
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"
但是它并没有如我所愿的出现"$29.95_Carryover_Plan_1GB"
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"
我该如何写入文件,并将文件名更改为 NAME_$29.95_Carryover_Plan_1GB_NAME
?
推荐答案
a="NAME_"$val1"_NAME" | sed s/" "/_/g | sed s/'"'/''/g
不执行我期望的操作.您实际上需要echo
变量:
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)"
或者更好(IMO):
a="$(echo "NAME_${val1}_NAME" | sed 's/ /_/g;s/"//g')"
或者如果您运行的是zsh而不是bash:
Or if you're running zsh rather than bash:
a="NAME_${${val1// /_}//\"/}_NAME"
这篇关于写入文件+文件名是需要稍作操作的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!