简体   繁体   中英

Change blank spaces with underscores in Bash

I'd like to write a script in Bash that:

  1. Takes a file as an input.

  2. If the file name has any blank space it changes it with an underscore.

My first question is: can a Bash script take arguments as input or any input has to be provided once the script is running by means of the read command? The other question would be how to use the mv command to perform point 2.

Your script could be simply:

#!/bin/bash

mv "$1" "$(sed 's/ \{1,\}/_/g' <<<"$1")"

Use it like script.sh file\\ name . The file file name will be renamed to file_name .

As gniourf_gniourf has pointed out in the comments (thanks), if you are using bash it is also possible to use the built-in character substitution:

mv "$1" "${1// /_}"

The behaviour of this is slightly different, as it will replace every individual space with an underscore, whereas the approach using sed also squashes groups of spaces into a single underscore. If you enable extended globbing, you can make this version behave the same as the one using sed:

shopt -s extglob
mv "$1" "${1//+( )/_}"

Depending on whether you are looking to replace space characters or all kinds of white space (like tabs, newlines, etc.), you may want to use [[:space:]] rather than in each of these examples.

Yes, of course bash scripts can be provided with arguments. I'd suggest to read at least bash manual (man bash) and it will answer most of your questions.

Re: your actual task - it would really help to know your OS. If you are running this on *nix something like the following would solve your issue:

$ touch "example file 1" "example  file  2"
$ ls -ld example*
-rw------- 1 user group 0 Oct 29 00:06 example  file  2
-rw------- 1 user group 0 Oct 29 00:06 example file 1
$ find . -maxdepth 1 -type f -name '* *' -print0 | xargs -0i /bin/bash -c 'F="{}" ; mv -iv "$F" "${F//[[:space:]]/_}"'
'./example  file  2' -> './example__file__2'
'./example file 1' -> './example_file_1'
$ ls -ld example*
-rw------- 1 user group 0 Oct 29 00:06 example__file__2
-rw------- 1 user group 0 Oct 29 00:06 example_file_1
$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM