我试图列出目录中所有文件的前5行(在Unix中创建命令)。我正在尝试通过使用head命令来解决此问题,如下所示:
(def primes
(cons 1 (lazy-seq
(filter (fn [i]
(not-any? (fn [p] (zero? (rem i p)))
(take-while #(<= % (Math/sqrt i))
(rest primes))))
(drop 2 (range))))))
=> #'user/primes
(first (time (drop 10000 primes)))
"Elapsed time: 0.023135 msecs"
=> 104729
这可以处理文件,但会给目录一个错误(显然)。
所以,我的问题是如何仅将head命令应用于文件?
我的bash脚本看起来像这样:
head -n 5 directory/*
任何建议都将不胜感激,并且非常感谢。
答案 0 :(得分:3)
这应该有效
#!/bin/bash
...
for f in "$directory"/{*,.??*}
do
if [ -f "$f" ]
then
case "$operation" in head|tail)
echo "$directory/$f:"
$operation -n "$lines" "$f"
esac
fi
done
答案 1 :(得分:1)
您可以使用find
命令。您可以在单个级别上过滤文件并针对每个head
命令执行:
$ find directory/ -maxdepth 1 -type f -exec head -5 {} \;
答案 2 :(得分:1)
您可以使用test命令测试文件的类型(常规文件,目录...)
if test -f filename
,并且仅在if
的结果为true
#!/bin/bash
# description: show first/last lines of all the files in a provided directory
if [ $# -ne 3 ]
then
echo "Error: Please provide 3 parameters."
echo "Usage Example: lshead -head 5 [DIR]"
exit
else
operation=$1
lines=$2
directory=$3
if [ "$operation" == "-head" ]
then
for f in $(ls $directory)
do
if test -f "$directory/$f"
then
echo "head $directory/$f:"
head -n $lines $directory/$f
fi
done
elif [ "$operation" == "-tail" ]
then
for f in $(ls $directory)
do
if test -f "$directory/$f"
then
echo "tail $directory/$f:"
tail -n $lines $directory/$f
fi
done
fi
fi