对创建的文件中的行进行排序的脚本

Script to sort lines in a created file

我有一个创建文件并在其中写入内容的脚本。

我必须在同一个脚本中包含哪些指令才能使该文件中的行按字母顺序排序?

让我更明确一点,这是我的代码:

nr=0
while read line; 
do
    for fisier in `find  -type f`
        do  
            counter=0
            for word in $(<$fisier)
                do
                    file=`basename "$fisier"`
                    length=`expr length $word`
                    echo "$length"
                    if [ $length -gt $n ];
                        then counter=$(($counter+1))
                    fi
                done 
        if [ $counter -gt $nr ];
        then echo "$file" >> $destinatie
        fi
        done
break
done

我应该把 | sort 命令放在哪里?

只需通过 sort 传输您的输出。如果您有多个创建输出的命令,您可以使用这样的子 shell:

(
# cmd 1
# cmd 2
) | sort > outfile

像您编辑的问题一样使用 while 循环,我建议只在 done 关键字之后添加它:

while condition
do
  # ...
done | sort >> "$destinatie"

请注意,您还必须删除循环内的重定向 >> $destinatie,并将调试输出回显到 stderr:

>&2 echo "$length"

此外,因为您使用 >> 进行追加,如果您在启动时没有 rm $destinatie(我记得您按照 中的指示进行了操作),那么整个文件终止后 不会 排序,而只会对每个 运行 期间添加的行进行排序。

使用 man sort 阅读更多关于 sort 的选项。

您可以使用 sort Unix 命令:

function_generating_lines | sort > output_file.txt