如何简化shell命令

cd \txt
filelist=`ls`
for file in $filelist
do
    >temp.txt
    echo $file
    cat $file | uniq >> temp.txt
    >$file
    cat temp.txt >> $file
done

如上面代码所示:功能需求是将该目录下所有文件进行cat uniq操作之后保存回该文件,我使用了temp.txt,不知道有没有可以直接写回文件的命令?请指导!

阅读 7.7k
7 个回答

改用python吧

建议加上sort命令
cat $file | uniq| sort -o $file

bashcd \txt
filelist=`ls`
for file in $filelist
do
    echo $file
    cat $file | uniq - $file
done

配合zsh使用

覆写文件可以借助 tee 命令,修改后代码如下

shellcd /txt
filelist=`ls`
for file in $filelist
do
  cat $file|uniq|tee $file>/dev/null
done

1首先准备下环境

{ txt }  » pwd                                                                              ~/txt
/home/Honwhy/txt
{ txt }  » ls                                                                               ~/txt
1.txt  2.txt  3.txt
{ txt }  » cat 1.txt                                                                        ~/txt
abcd
abcd
abc
abcde
abc
a
b
c

三份txt内容都是一样的。
2尝试下这个答案的命令http://askubuntu.com/questions/528658/redirect-pipe-output-to-the-same...

filelist=`ls`
for file in $filelist
do
  sort -u $(pwd)/$file | tee $(pwd)/$file >/dev/null
done

sort -u带有uniq的意思。

3.还需要调整。

cd \txt
filelist=`ls`
for file in $filelist
do
    >temp.txt
    echo $file
    cat $file | uniq | tee temp.txt
    >$file
    cat temp.txt >> $file
done

只修改第七行的最后一个重定向即可,tee 可以做 pipe fitting,详见手册

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题