Rohan Kishibe Rohan Kishibe - 29 days ago 4
Bash Question

awk command does not work properly when assigning output to variable

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 "$(basename "$old_file")" | awk 'gsub(" ","_")'


but when it comes to assigning the output to variables, it doesn't work...

Does anybody know the idea?

Answer Source

Actually no need of awk, please note below one replaces all space to underscore, not just filename, it can be path too

$ old_file="/home/somedir/otherdir/foobar 20170919.csv"
$ newfile="${old_file// /_}"
$ echo "$newfile"
/home/somedir/otherdir/foobar_20170919.csv