0

cat我使用该命令将多个数据文件附加到一个数据文件中。如何将该单个文件值分配到新文件中?

我正在使用命令:

cat file1 file2 file3 > Newfile.txt
AnotherFile=`cat Newfile.txt`
sort $AnotherFile | uniq -c

它显示错误,例如无法打开另一个文件如何将此新文件值分配到另一个文件中?

4

3 回答 3

3

原始问题的原始答案

好吧,最简单的方法可能是cp

cat file1 file2 file3 > Newfile.txt
cp Newfile.txt AnotherFile.txt

如果做不到这一点,您可以使用:

cat file1 file2 file3 > Newfile.txt
AnotherFile=$(cat Newfile.txt)
echo "$AnotherFile" > AnotherFile.txt

修订后问题的修订答案

原来的问题echo "$AnotherFile"是第三行;修改后的问题已sort $AnotherFile | uniq -c作为第三行。

假设sort $AnotherFile不是对通过连接原始文件创建的列表中提到的文件的所有内容进行排序(即,假设file1,file2file3不只包含文件名列表),那么目标是对找到的行进行排序和计数在源文件中。

整个工作可以在一个命令行中完成:

cat file1 file2 file3 | tee Newfile.txt | sort | uniq -c

或者(更常见的是):

cat file1 file2 file3 | tee Newfile.txt | sort | uniq -c | sort -n

它按频率递增的顺序列出了行。

如果您确实想对 , 中列出的文件的内容进行排序,file1但只列出每个文件的内容一次,则:file2file3

cat file1 file2 file3 | tee Newfile.txt | sort -u | xargs sort | sort | uniq -c

连续三个与排序相关的命令看起来很奇怪,但每个步骤都有理由。sort -u确保每个文件名都列出一次。将xargs sort标准输入上的文件名列表转换为sort命令行上的文件名列表。其输出是生成的每批文件的排序数据xargsxargs如果不需要sort多次运行的文件很少,那么下面的纯文本sort是多余的。但是,如果xargs必须运行sort不止一次,那么最终排序必须处理这样一个事实,即由 生产的第二批生产的第一行xargs sort可能在生产的第一批生产的最后一行之前xargs sort

这成为基于原始文件中数据知识的判断调用。如果文件足够小以至于xargs不需要运行多个sort命令,请省略最后的sort. 启发式方法是“如果源文件的大小总和小于最大命令行参数列表,则不包括额外的排序”。

于 2013-04-18T06:57:14.927 回答
0

您可能可以一口气做到这一点:

# Write to two files at once. Both files have a constantly varying
# content until cat is finished.
cat file1 file2 file3 | tee Newfile.txt> Anotherfile.txt

# Save the output filename, just in case you need it later
filename="Anotherfile.txt"

# This reads the contents of Newfile into a variable called AnotherText
AnotherText=`cat Newfile.txt`

# This is the same as "cat Newfile.txt"
echo "$AnotherText" 

# This saves AnotherText into Anotherfile.txt

echo "$AnotherText" > Anotherfile.txt

# This too, using cp and the saved name above
cp Newfile.txt "$filename"

如果您想一次性创建第二个文件,这是一种常见的模式:

# During this process the contents of tmpfile.tmp is constantly changing
{ slow process creating text } > tmpfile.tmp

# Very quickly create a complete Anotherfile.txt
mv tmpfile.tmp Anotherfile.txt
于 2013-04-18T07:01:43.507 回答
0

制作文件并在附加模式下重定向。

touch Newfile.txt
cat files* >> Newfile.txt
于 2017-05-01T10:11:16.217 回答