lev*_*ato 21 command-line bash
假设我有一个文本文件,如:
john
george
james
stewert
Run Code Online (Sandbox Code Playgroud)
每个名字都在一个单独的行上。
我想读这个文本文件中的行,并创建一个文本文件,每个名称,如:john.txt,george.txt等等。
我怎样才能在 Bash 中做到这一点?
kos*_*kos 18
touch:while read line; do touch "$line.txt"; done <in
Run Code Online (Sandbox Code Playgroud)
while read line; [...]; done <in: 这会read一直运行直到read它自己返回1,当到达文件末尾时会发生这种情况;由于重定向,输入 forread是从in当前工作目录中命名的文件中读取的,而不是从终端中读取的<in;touch "$line.txt": 这运行touch在 的扩展值上$line.txt,它是line后跟.txt;的内容。touch如果不存在则创建文件,如果存在则更新其访问时间;xargs+ touch:xargs -a in -I name touch name.txt
Run Code Online (Sandbox Code Playgroud)
-a in:xargs从in当前工作目录中命名的文件中读取其输入;-I name:在以下命令中用当前输入行xargs替换每次name出现的 ;touch name:touch在 的替换值上运行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
Run Code Online (Sandbox Code Playgroud)
ter*_*don 18
在这种特殊情况下,每行只有一个单词,您还可以执行以下操作:
xargs touch < file
Run Code Online (Sandbox Code Playgroud)
请注意,如果您的文件名可以包含空格,这将中断。对于这种情况,请改用它:
xargs -I {} touch {} < file
Run Code Online (Sandbox Code Playgroud)
只是为了好玩,这里有一些其他方法(这两种方法都可以处理任意文件名,包括带空格的行):
珀尔
perl -ne '`touch "$_"`' file
Run Code Online (Sandbox Code Playgroud)awk
awk '{printf "" > $0}' file
Run Code Online (Sandbox Code Playgroud)请注意,在 Linux 和类似系统上,对于绝大多数文件,扩展名是可选的。没有理由为.txt文本文件添加扩展名。你可以自由地这样做,但它根本没有区别。因此,如果您无论如何都想要扩展,请使用以下之一:
xargs -I {} touch {}.txt < file
perl -ne '`touch "$_.txt"`' file
awk '{printf "" > $0".txt"}' file
Run Code Online (Sandbox Code Playgroud)
假设我有一个文本文件......
让我们说,我有一个答案;)
awk '{system("touch \""$0".txt\"")}' file
Run Code Online (Sandbox Code Playgroud)
防水也带有空格和后缀=)
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
Run Code Online (Sandbox Code Playgroud)
另一种方式,tee。请注意,如果文件列表中的一行包含多个字符串,则此方法将中断。
testerdir:$ echo "" | tee $(cat filelist)
testerdir:$ ls
filelist george james john stewert
Run Code Online (Sandbox Code Playgroud)
或者,</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
Run Code Online (Sandbox Code Playgroud)