I'm trying to create a really simple bash script, which will list the first few lines of every file in a specific directory. The directory should be specified by the argument. I think that the Grep command should be used, but I have really no idea how.
我正在尝试创建一个非常简单的bash脚本,它将列出特定目录中每个文件的前几行。该目录应由参数指定。我认为应该使用Grep命令,但我真的不知道如何。
My existing script does not seem to work at all, so it's no use putting it in here.
我现有的脚本似乎根本不起作用,所以把它放在这里是没用的。
5 个解决方案
#1
7
Use head command:
使用head命令:
head -3 /path/to/dir/*
#2
3
For any answer using head
and *
, redirect stderr to /dev/null unless you want to see errors like:
对于使用head和*的任何答案,将stderr重定向到/ dev / null除非你想看到如下错误:
head: error reading ‘tmp’: Is a directory
#3
0
for file in dir/*; do
echo "-- $file --"
head "$file"
echo
done
#4
0
If you want the first few lines of all files ending in .txt
, try
如果你想要以.txt结尾的所有文件的前几行,请尝试
head *.txt
or
head --lines=3 *.txt
#5
0
Because bash does filename expansion (globbing) by default, you can just let your shell expand input and let head do the rest:
因为bash默认情况下会进行文件名扩展(globbing),所以你可以让你的shell扩展输入,让head完成剩下的工作:
head *
The * wildcard expands to all the filenames in the working directory. On zsh you can see this nicely, when it autocompletes your commandline when you press tab.
*通配符扩展为工作目录中的所有文件名。在zsh上,当你按Tab键自动填充命令行时,你可以很好地看到它。
You can change the amount of lines with the -n argument to head.
您可以使用-n参数更改行数。
If you want to do this recursively:
如果你想以递归方式执行此操作:
find . \! -type d -exec head '{}' +
#1
7
Use head command:
使用head命令:
head -3 /path/to/dir/*
#2
3
For any answer using head
and *
, redirect stderr to /dev/null unless you want to see errors like:
对于使用head和*的任何答案,将stderr重定向到/ dev / null除非你想看到如下错误:
head: error reading ‘tmp’: Is a directory
#3
0
for file in dir/*; do
echo "-- $file --"
head "$file"
echo
done
#4
0
If you want the first few lines of all files ending in .txt
, try
如果你想要以.txt结尾的所有文件的前几行,请尝试
head *.txt
or
head --lines=3 *.txt
#5
0
Because bash does filename expansion (globbing) by default, you can just let your shell expand input and let head do the rest:
因为bash默认情况下会进行文件名扩展(globbing),所以你可以让你的shell扩展输入,让head完成剩下的工作:
head *
The * wildcard expands to all the filenames in the working directory. On zsh you can see this nicely, when it autocompletes your commandline when you press tab.
*通配符扩展为工作目录中的所有文件名。在zsh上,当你按Tab键自动填充命令行时,你可以很好地看到它。
You can change the amount of lines with the -n argument to head.
您可以使用-n参数更改行数。
If you want to do this recursively:
如果你想以递归方式执行此操作:
find . \! -type d -exec head '{}' +