0

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?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
Rohan Kishibe
  • 617
  • 2
  • 10
  • 25
  • 1
    doesnt work in this way ? x=$(echo "$(basename "$old_file")" | awk 'gsub(" ","_")') echo $x – Frank Sep 19 '17 at 13:25
  • 1
    Also for `Awk` to work 1. enclose the actions within `{..}` i.e. as `.. | awk '{gsub(" ","_")}'` 2. `gsub()` does not print to console by default. You need to call `print` explicitly (or) do `{gsub(" ","_")}1` – Inian Sep 19 '17 at 13:30
  • That's a [useless use of `echo`](http://www.iki.fi/era/unix/award.html#echo) btw; you just want `basename "$old_file" | awk ...` or better yet `basename=${old_file##*/}; basename=$(basename//_/}` – tripleee Sep 20 '17 at 04:36

1 Answers1

2

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
Akshay Hegde
  • 16,536
  • 2
  • 22
  • 36
  • 1
    It works fine! Thank you. I want to use file name, so I edited the command a little like `new_file=$(basename "${old_file// /_}")` – Rohan Kishibe Sep 19 '17 at 13:51
  • @RohanKishibe you are welcome, use can use this, input will be file with path, and variable new_file will have just filename with underscore `file=${file_with_path##*/}; new_file="${file// /_}"` – Akshay Hegde Sep 19 '17 at 14:00
  • @RohanKishibe: example : `file_with_path="asa/tasas asas/tetst/mayas asas.txt"; file=${file_with_path##*/}; new_file="${file// /_}"; echo "$new_file"` – Akshay Hegde Sep 19 '17 at 14:03
  • 1
    There is much to learn... anyway, thank you for good examples! – Rohan Kishibe Sep 19 '17 at 14:07
  • 1
    @EdMorton thank you, though added in comment missed in answer, fixed now :) – Akshay Hegde Sep 19 '17 at 15:40