【发布时间】:2013-08-14 04:40:46
【问题描述】:
所以我的问题如下: 我有一堆文件,我只需要每个文件中某一行的信息(所有文件的同一行)。 例子: 我想要文件 example_1.dat~example_10.dat 中第 10 行的内容,然后我想将其保存在 > test.dat
我尝试使用:head -n 5 example_*.dat > test.dat。但这给了我从顶部到我选择的行的所有信息,而不仅仅是行。
请帮忙。
【问题讨论】:
所以我的问题如下: 我有一堆文件,我只需要每个文件中某一行的信息(所有文件的同一行)。 例子: 我想要文件 example_1.dat~example_10.dat 中第 10 行的内容,然后我想将其保存在 > test.dat
我尝试使用:head -n 5 example_*.dat > test.dat。但这给了我从顶部到我选择的行的所有信息,而不仅仅是行。
请帮忙。
【问题讨论】:
$ for f in *.dat ; do sed -n '5p' $f >> test.dat ; done
此代码将执行以下操作:
在以 .dat 结尾的目录中查找文件 f。 在文件的第 5 行使用 sed 并写入 test.dat。 如果存在,“>>”将在文件底部添加行。
【讨论】:
使用head 和tail 的组合来缩放到所需的行。例如head -n 5 file | tail -n 1
您可以使用for 循环来完成多个文件
for f in *.dat ; do head -n 5 $f | tail -n 1 >> test.dat ; done
PS:在运行循环之前不要忘记清理test.dat 文件(> test.dat)。否则,您也会得到以前运行的结果。
【讨论】:
for 解决方案。
您可以使用sed 或awk:
sed -n "5p"
awk "NR == 5"
【讨论】:
这可能对你有用(GNU sed):
sed -sn '5wtest.dat' example_*.dat
【讨论】: