我正在尝试获取目录中的文件名列表和每个文件的第一行文本,并将每一对输出到一行以输出到 .csv 文件。
我尝试了多种使用 head、ls、find 和 grep 以及它们的组合的不同方法,但似乎无法将结果打印到一行上。我得到的最接近的是让它们在不同的行上打印。
这是我需要的输出示例:
filename1.txt "this is the first line of text"
filename2.txt "this is the first line of text"
Run Code Online (Sandbox Code Playgroud)
我并不真正关心结果中是否有额外的字符或任何内容,因为一旦我将它们放在同一行上,我就可以在 Excel 中轻松编辑它们。
任何帮助将不胜感激。
要获取目录中所有文件的文件名和第一行,请尝试:
awk '{print FILENAME" \"" $0"\""; nextfile}' *
Run Code Online (Sandbox Code Playgroud)
要获取名称以 328 开头的所有文件的文件名和第一行,请尝试:
awk '{print FILENAME" \"" $0"\""; nextfile}' 328*
Run Code Online (Sandbox Code Playgroud)
考虑一个包含这两个文件的目录:
$ cat filename1.txt
this is the first line of text
2
3
$ cat filename2.txt
this is the first line of text
b
c
Run Code Online (Sandbox Code Playgroud)
现在,运行我们的命令:
$ awk '{print FILENAME" \"" $0"\""; nextfile}' *
filename1.txt "this is the first line of text"
filename2.txt "this is the first line of text"
Run Code Online (Sandbox Code Playgroud)
`awk '{...}' *
这将启动awk并运行花括号内的命令。使用 glob *,这是为所有文件运行的。例如,可以将 glob 限制为328*.txt处理名称328以.txt.开头和结尾的所有文件。
默认情况下,awk 将依次为每个文件一次读取一行。
print FILENAME" \"" $0"\""
这告诉 awk 打印文件名,"后跟第一行,$0,然后是另一个".
nextfile
由于我们对阅读第二行没有兴趣,这告诉 awk 跳到下一个文件。
我们可以将第一行保存到一个文件中,如下所示:
$ awk '{print FILENAME" \"" $0"\""; nextfile}' *.txt >output.txt
Run Code Online (Sandbox Code Playgroud)
该output.txt文件如下所示:
$ cat output.txt
filename1.txt "this is the first line of text"
filename2.txt "this is the first line of text"
Run Code Online (Sandbox Code Playgroud)