awk,sed:一个衬管命令,用于从给定文件夹中的_all_文件名中删除空格?

Vir*_*ren 7 awk command sed

之前:

eng-vshakya:scripts vshakya$ ls
American Samoa.png                  Faroe Islands.png                   Saint Barthelemy.png
Run Code Online (Sandbox Code Playgroud)

后:

eng-vshakya:scripts vshakya$ ls
AmericanSamoa.png                   FaroeIslands.png                    SaintBarthelemy.png
Run Code Online (Sandbox Code Playgroud)

尝试下面的原型,但它不起作用:(抱歉,当涉及到awk/sed时不是很好:(

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

[上面是原型,真正的命令,我想,将是:

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

]

gho*_*oti 17

当您在纯粹的bash中执行此操作时,无需使用awk或sed.

[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]$ 
Run Code Online (Sandbox Code Playgroud)

请注意,${foo/ /}表示法是bash,并且在经典Bourne shell中不起作用.


Wil*_*ell 7

ghoti的解决方案是正确的做法.既然你问如何在sed中这样做,这是一种方式:

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

tr那里删除文件名中的换行符,并且必须确保sed在一行中看到整个文件名.