linux - 如何简化shell命令
PHPz
PHPz 2017-04-17 13:29:22
[Linux讨论组]
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,不知道有没有可以直接写回文件的命令?请指导!

PHPz
PHPz

学习是最好的投资!

全部回复(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
ringa_lee

配合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,详见手册

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号