This question already has an answer here:
这个问题在这里已有答案:
- How to set a variable to the output of a command in Bash? 13 answers
- 如何在Bash中将变量设置为命令的输出? 13个答案
I'm trying to convert space to underscore in a file name, my script is like below.
我正在尝试将空间转换为文件名中的下划线,我的脚本如下所示。
old_file=/home/somedir/otherdir/foobar 20170919.csv
new_file="$(basename "$old_file")" | awk 'gsub(" ","_")'
This script works fine when I use with echo
command,
当我使用echo命令时,此脚本工作正常,
echo "$(basename "$old_file")" | awk 'gsub(" ","_")'
but when it comes to assigning the output to variables, it doesn't work...
但是当涉及将输出分配给变量时,它不起作用......
Does anybody know the idea?
有人知道这个想法吗?
1 个解决方案
#1
2
Actually no need of awk
, please note below one replaces all space
to underscore
, not just filename, it can be path too
实际上不需要awk,请注意下面的一个替换所有空格下划线,不仅仅是文件名,它也可以是路径
$ old_file="/home/somedir/otherdir/foobar 20170919.csv"
$ newfile="${old_file// /_}"
$ echo "$newfile"
/home/somedir/otherdir/foobar_20170919.csv
#1
2
Actually no need of awk
, please note below one replaces all space
to underscore
, not just filename, it can be path too
实际上不需要awk,请注意下面的一个替换所有空格下划线,不仅仅是文件名,它也可以是路径
$ old_file="/home/somedir/otherdir/foobar 20170919.csv"
$ newfile="${old_file// /_}"
$ echo "$newfile"
/home/somedir/otherdir/foobar_20170919.csv