我有两套文件;
file1.txt file1.json
file2.txt file2.json
file3.txt file3.json
...
fileN.txt fileN.json
json文件包含以下格式:
{"ago": "59 sec ago", "base_time": 1401243133, "title": "Untitled", "type": "None", "retrieval_time": 1401624105, "id": "qwNAgvYZ"}
我想用相应的fileX.json文件中的“ title”参数重命名每个fileX.txt。
对于前。
rename fileX.txt -> Untitled
我可以按如下方式过滤掉该值;$ cat fileX.json | awk -F"\"" '{print $10}'
但是,如果遇到现有文件名,则应使用后缀将其重命名。
例如,假设存在一个Untitled.txt
。因此,新文件应重命名为Untitled-1.txt
。下次相遇Untitled-2.txt
也是一样。
这是一个相当简单直接的shell脚本,它使用jsonpipe来完成您想要的事情。它不使用任何高级sh / bash功能,仅执行文件名的最低限度完整性检查。
注意:jq比的功能要强大得多jsonpipe
,但是jsonpipe
当您不特别关心(或不想知道)json数据的结构并且只想提取一个或两个字段,并且/或者想要与面向行的文本处理工具,如使用JSON数据awk
,sed
,grep
等。
一个明显的可能增强是使用printf
零填充整数字段将文件重命名为固定宽度编号的名称,例如Untitled-0001.txt
而不是Untitled-1.txt
。如果您愿意,我会留给您做。
按照书面规定,它实际上不会重命名任何文件。它将仅打印将使用的mv
命令。编辑它以删除每个命令之前的,以使其实际上重命名文件。echo
mv
#! /bin/sh
for f in file*.txt ; do
b=$(basename "$f" .txt)
# ignore current .txt file if there's no matching .json file
if [ -e "$b.json" ] ; then
# extract the title field.
title=$(jsonpipe < "$b.json" |
awk -F'\t' '$1=="/title" {gsub(/\"/,"",$2) ; print $2}')
if [ -n "$title" ] ; then
if [ ! -e "$title.txt" ] ; then
echo mv -v "$f" "$title.txt"
else
# are there any other "$title-*.txt" filenames?
others=$(find . -maxdepth 1 -name "$title-*.txt")
if [ -z "$others" ] ; then
echo mv -v "$f" "$title-1.txt"
else
# use version-sort to get highest $title- number used.
highest=$(printf "%s\n" "$others" | sort -V | tail -n 1)
hnum=$(printf "%s\n" "$highest" | sed -e 's/^.*-// ; s/\.txt$//')
hnum=$(( highest_num + 1))
echo mv -v "$f" "$title-$hnum.txt"
fi
fi
fi
fi
done
有效的使用/证明示例:
$ ls -l
total 8
-rw-rw-r-- 1 cas cas 132 May 19 23:47 file1.json
-rw-rw-r-- 1 cas cas 0 May 20 00:04 file1.txt
-rwxrwxr-x 1 cas cas 797 May 20 00:04 json-rename.sh
$ cat file1.json
{"ago": "59 sec ago", "base_time": 1401243133, "title": "Untitled",
"type": "None", "retrieval_time": 1401624105, "id": "qwNAgvYZ"}
$ ./json-rename.sh
mv -v file1.txt Untitled.txt
$ touch Untitled.txt
$ ./json-rename.sh
mv -v file1.txt Untitled-1.txt
$ touch Untitled-1.txt
$ ./json-rename.sh
mv -v file1.txt Untitled-2.txt
$ touch Untitled-999.txt
$ ./json-rename.sh
mv -v file1.txt Untitled-1000.txt
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句