从文本文件中读取行并为每行中的每个名称创建一个文本文件


21

假设我有一个类似的文本文件:

john
george
james
stewert

每个名称都放在单独的行中。

我想读这个文本文件中的行,并创建一个文本文件,每个名称,如:john.txtgeorge.txt等等。

我如何在Bash中做到这一点?


2
您需要扩展程序吗?在Linux中,文本文件没有扩展名的原因。
terdon

Answers:


18

#1使用Bash + touch

while read line; do touch "$line.txt"; done <in
  • while read line; [...]; done <in:这会read一直运行直到read自身返回1,这在到达文件末尾时发生;输入read是从in当前工作目录中命名的文件而不是由于<in重定向而从终端读取的;
  • touch "$line.txt":这touch基于的扩展值$line.txtline其后是.txt; 的内容;touch如果不存在则创建文件,如果存在则更新访问时间;

#2使用xargs+ touch

xargs -a in -I name touch name.txt
  • -a inxargsin当前工作目录中命名的文件中读取其输入;
  • -I name:在以下命令中用当前输入行xargs替换每次name出现的;
  • touch nametouch以的替换值运行name; 如果不存在,它将创建文件,如果存在,它将更新其访问时间;
% ls
in
% cat in
john
george
james
stewert
% while read line; do touch "$line.txt"; done <in
% ls
george.txt  in  james.txt  john.txt  stewert.txt
% rm *.txt
% xargs -a in -I name touch name.txt
% ls
george.txt  in  james.txt  john.txt  stewert.txt

read line实际将如何读取该行?@kos
kashish

@kashish <indone品牌readwhile循环条件读取和存储从一条线inline,在每一次迭代; 这样,touch "$line.txt"循环内部将扩展到最后的读取行.txt
kos 2015年

一个人会while read line; do touch "$line.txt"; done <in做吗?源文件在哪里?
kashish 2015年

@kashish当然,它们是替代方法:您只能使用一种。
kos 2015年

1
@kashish就是这样read。请参阅help read
terdon

18

在这种特殊情况下,每行只有一个单词,您还可以执行以下操作:

xargs touch < file

请注意,如果您的文件名可以包含空格,则此操作将中断。在这种情况下,请改用以下方法:

xargs -I {} touch {} < file

只是为了好玩,这里还有其他几种方法(这两种方法都可以处理任意文件名,包括带有空格的行):

  • 佩尔

    perl -ne '`touch "$_"`' file
  • Awk

    awk '{printf "" > $0}' file 

请注意,在Linux和类似系统上,该扩展名对于绝大多数文件是可选的。没有理由在.txt文本文件中添加扩展名。您可以这样做,但是完全没有区别。因此,如果仍要扩展,请使用以下方法之一:

xargs -I {} touch {}.txt < file
perl -ne '`touch "$_.txt"`' file
awk '{printf "" > $0".txt"}' file 

7

AWK也适合此任务:

testerdir:$ awk '{system("touch "$0)}' filelist

testerdir:$ ls
filelist  george  james  john  stewert

testerdir:$ awk '{system("touch "$0".txt")}' filelist                          

testerdir:$ ls
filelist  george.txt  james.txt  john.txt  stewert.txt
george    james       john       stewert

另一种方式tee。请注意,如果一行在文件列表中包含多个字符串,则此方法将中断。

testerdir:$ echo "" | tee $(cat filelist)


testerdir:$ ls
filelist  george  james  john  stewert

或者,</dev/null tee $(cat filelist)如果您要避免管道运输,也可以完成

cp /dev/null 方法(正如我演示的那样,它确实适用于包含空格的文件名):

testerdir:$ cat filelist | xargs -I {}  cp /dev/null  "{}"                     

testerdir:$ ls
filelist  FILE WITH SPACES  george  james  john  stewert

testerdir:$ ls FILE\ WITH\ SPACES                                              
FILE WITH SPACES

1
@kos如果文件中的每一行每行仅包含一个字符串,则它将每行创建一个文件。实际上与相同echo "" | tee file1 file2 file2。但是,如果文件名包含空格,则确实会中断。
Sergiy Kolodyazhnyy 2015年

7

假设我有一个文本文件...

假设我有一个答案;)

awk '{system("touch \""$0".txt\"")}' file

带有空格和后缀=的防水

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.