Awk, sed: one liner command to remove spaces from _all_ file names in a given folder?

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 the prototype below, but it doesn't work :( Sorry, not very good when it comes to awk / sed :(

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

[Over the prototype, the real team, I think, would be:

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

]

+6
source share
2 answers

The ghoti solution is the right thing. Since you are asking how to do this in sed, here is one way:

 for file in *; do newfile=$( echo "$file" | tr -d \\n | sed 's/ //g' ); test "$file" != "$newfile" && mv "$file" "$newfile"; done 

tr exists to remove newlines in the file name and you need to make sure sed sees all the file name on one line.

+7
source

No need to use awk or sed if 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 notation is ${foo/ /} bash and does not work in the classic Bourne shell.

+15
source

Source: https://habr.com/ru/post/921819/


All Articles