将输出分配给变量[duplicate]时,awk命令无法正常工作

时间:2022-02-24 20:11:11

This question already has an answer here:

这个问题在这里已有答案:

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