Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk, sed: one liner command for removing spaces from _all_ file names in a given folder?

Tags:

command

sed

awk

Before:

eng-vshakya:scripts vshakya$ ls
American Samoa.png                  Faroe Islands.png                   Saint Barthelemy.png

After:

eng-vshakya:scripts vshakya$ ls
AmericanSamoa.png                   FaroeIslands.png                    SaintBarthelemy.png

Tried below prototype, but it does not work :( Sorry, not very good when it comes to awk/sed :(

ls *.png | sed 's/\ /\\\ /g' | awk '{print("mv "$1" "$1)}'

[ Above is prototype, real command, I guess, would be:

ls *.png | sed 's/\ /\\\ /g' | awk '{print("mv "$1" "$1)}' | sed 's/\ //g'

]

like image 434
Viren Avatar asked Aug 01 '12 05:08

Viren


People also ask

How do you remove spaces using sed?

sed 's/ //g' input. txt > no-spaces. txt.

How do I remove a space in Unix?

s/[[:space:]]//g; – as before, the s command removes all whitespace from the text in the current pattern space.


1 Answers

No need to use awk or sed when you can do this in pure bash.

[ghoti@pc ~/tmp1]$ ls -l
total 2
-rw-r--r--  1 ghoti  wheel  0 Aug  1 01:19 American Samoa.png
-rw-r--r--  1 ghoti  wheel  0 Aug  1 01:19 Faroe Islands.png
-rw-r--r--  1 ghoti  wheel  0 Aug  1 01:19 Saint Barthelemy.png
[ghoti@pc ~/tmp1]$ for name in *\ *; do mv -v "$name" "${name// /}"; done
American Samoa.png -> AmericanSamoa.png
Faroe Islands.png -> FaroeIslands.png
Saint Barthelemy.png -> SaintBarthelemy.png
[ghoti@pc ~/tmp1]$ 

Note that the ${foo/ /} notation is bash, and does not work in classic Bourne shell.

like image 179
ghoti Avatar answered Sep 20 '22 10:09

ghoti