在bash中有一个单行解决方案,用于将所有以相同整数开头的句子移动到同一个文件(保留它们的顺序)吗?
0 ||| the shortage of snow in mountain stirred hoteliers
....
0 ||| the shortage of snow in mountain stirred hotel
1 ||| the runways deserted pose any problem that operators ski .
...
1 ||| the runways deserted do not pose a problem that operators of ski .
2 |||
...
Run Code Online (Sandbox Code Playgroud)
要将以相同数字开头的行移动到单独的文件0,1,2等中?
绝对:
awk '{print > $1".txt"}' file
Run Code Online (Sandbox Code Playgroud)
这用于awk获取每行的第一个字段并将其用作文件名(与".txt"一起使用).然后,print输出到给定文件.
对于您的给定输入,请查看输出:
$ tail *.txt
==> 0.txt <==
0 ||| the shortage of snow in mountain stirred hoteliers
0 ||| the shortage of snow in mountain stirred hotel
==> 1.txt <==
1 ||| the runways deserted pose any problem that operators ski .
1 ||| the runways deserted do not pose a problem that operators of ski .
==> 2.txt <==
2 |||
Run Code Online (Sandbox Code Playgroud)
正如评论中所见,如果有不同的第一个字段,awk可以抱怨有这么多打开的文件.如果是这样,您可以在打印后关闭它们:
awk '{file="$1".txt"; print >> file; close(file)}' file
Run Code Online (Sandbox Code Playgroud)
重要的是要注意我们需要使用>>追加.否则,每次我们将删除文件中的所有先前内容.