我需要编写一个脚本来按名称中第一个“ 0”之后的字符对文件名进行排序。所有文件名至少包含一个0。 然后,脚本应按该顺序打印每个文件的内容。
我知道我需要使用sort和cat。但我不知道哪种。据我所知。
#!/bin/bash
dir=$(pwd)
for n in $dir `ls | sort -u ` ; do
cat $n
done;
答案 0 :(得分:1)
假设
您需要执行以下疯狂操作(未经测试):
find . -mindepth 1 -maxdepth 1 -exec printf '%s\0' {} + | while IFS= read -r -d ''
do
printf '%s\0' "${REPLY#*0}"
done | sort --unique --zero-terminated | while IFS= read -r -d ''
do
for file in ./*"$REPLY"
do
[…]
done
done
说明:
答案 1 :(得分:0)
看看这个find
+ xargs
可以正确处理带有“有趣字符”的文件名:
find . -maxdepth 1 -type f -name '*0*' -print0 | sort -zt0 -k2 | xargs -0 cat
答案 2 :(得分:-2)
您可以编写一个如下所示的脚本:
#/bin/bash
# using "shopt -s nullglob" so that an empty directory won't give you a literal '*'.
shopt -s nullglob
# get a sorted directory listing
filelist=$(for i in .*0* *0*; do echo "$i"; done | sort -t0 -k2)
IFS=$(echo -en "\n\b")
# iterate over your sorted list
for f in $filelist
do
# just cat text files.
file $f | grep text > /dev/null 2>&1
if [ $? = 0 ]
then
cat $f
fi
done
测试:
[plankton@localhost SO_scripts]$ ls -l
total 40
-rw-r--r-- 1 plankton plankton 10 Sep 9 10:56 afile0zzz
-rw-r--r-- 1 plankton plankton 14 Sep 9 10:56 bfile xxx0yyy
-rwxr-xr-x 1 plankton plankton 488 Sep 9 10:56 catfiles.sh
-rw-r--r-- 1 plankton plankton 9 Sep 9 10:56 file0123
-rw-r--r-- 1 plankton plankton 9 Sep 9 10:56 file0124
-rw-r--r-- 1 plankton plankton 7 Sep 9 10:56 file0a
-rw-r--r-- 1 plankton plankton 8 Sep 9 10:56 file0aa
-rw-r--r-- 1 plankton plankton 7 Sep 9 10:56 file0b
-rw-r--r-- 1 plankton plankton 9 Sep 9 10:56 file0bbb
-rw-r--r-- 1 plankton plankton 18 Sep 9 10:56 files*_0asdf
[plankton@localhost SO_scripts]$ ./catfiles.sh
. is not a text file
.. is not a text file
Doing catfiles.sh
#/bin/bash
# using "shopt -s nullglob" so that an empty directory won't give you a literal '*'.
shopt -s nullglob
# get a sorted directory listing
filelist=$(for i in .* *; do echo "$i"; done | sort -t0 -k2)
IFS=$(echo -en "\n\b")
# iterate over your sorted list
for f in $(for i in .* *; do echo "$i"; done | sort -t0 -k2)
do
# just cat text files.
file $f | grep text > /dev/null 2>&1
if [ $? = 0 ]
then
echo "Doing $f"
cat $f
else
echo "$f is not a text file"
fi
done
Doing file0123
file0123
Doing file0124
file0124
Doing file0a
file0a
Doing file0aa
file0aa
Doing files*_0asdf
file with * in it
Doing file0b
file0b
Doing file0bbb
file0bbb
Doing bfile xxx0yyy
bfile xxx0yyy
Doing afile0zzz
afile0zzz
根据PesaThe对.*0* *0*
的建议进行了更新。
答案 3 :(得分:-3)
dir=$(pwd)
for n in `ls -1 $dir | sort -t0 -k2`; do
cat $n
done;