Shell编程:批量文件名称字符替换(实现源码+注释)

发布网友

我来回答

1个回答

热心网友

y:root:/tmp/file> ls -ltr
total 5
drwxr-xr-x 3 root root 0 Dec 12 11:53 ..
-rwxr-xr-x 1 root root 243 Dec 12 12:02 chgname
-rw-r--r-- 1 root root   0 Dec 12 12:02 a9.txt
-rw-r--r-- 1 root root   0 Dec 12 12:02 a88.txt
-rw-r--r-- 1 root root   0 Dec 12 12:02 a2.txt
-rw-r--r-- 1 root root   0 Dec 12 12:02 a100.txt
-rw-r--r-- 1 root root   0 Dec 12 12:02 a1.txt
drwxr-xr-x 2 root root 192 Dec 12 12:02 .
y:root:/tmp/file> ./chgname
a1.txt->a[1].txt
a100.txt->a[100].txt
a2.txt->a[2].txt
a88.txt->a[88].txt
a9.txt->a[9].txt
y:root:/tmp/file> ls -ltr
total 5
drwxr-xr-x 3 root root 0 Dec 12 11:53 ..
-rwxr-xr-x 1 root root 243 Dec 12 12:02 chgname
-rw-r--r-- 1 root root   0 Dec 12 12:02 a[9].txt
-rw-r--r-- 1 root root   0 Dec 12 12:02 a[88].txt
-rw-r--r-- 1 root root   0 Dec 12 12:02 a[2].txt
-rw-r--r-- 1 root root   0 Dec 12 12:02 a[1].txt
-rw-r--r-- 1 root root   0 Dec 12 12:02 a[100].txt
drwxr-xr-x 2 root root 208 Dec 12 12:02 .
y:root:/tmp/file> cat chgname 
#!/bin/bash

ls -1 --color=never a*.txt | awk '/^a[0-9]+\.txt$/{
    cmd="mv " $0 " \47" gensub(/^a([0-9]+)\.txt$/, "a\\[\\1\\].txt", "", $0) "\47"
    cmd | getline
    close(cmd)
    print $0 "->" gensub(/^a([0-9]+)\.txt$/, "a\\[\\1\\].txt", "", $0)
}'

 源码解释:

ls -1 --color=never a*.txt 列出所有符合条件文件然后通过管道|传输给awk

awk根据输入重组系统命令"mv a1.txt 'a[1].txt'"然后通过getline执行

命令执行完毕close(cmd)...

这个做法比较简单直接,如果使用while loop就比较麻烦一点点,如果你一定要while也是可以做到的。

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com