Linux 使用shell脚本为每一行添加后缀

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16991035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 23:09:44  来源:igfitidea点击:

Add suffix to each line with shell script

linuxbashshell

提问by Bing.Physics

I need to add some words at the end of each line of a text file. How can I do this with a Bash script?

我需要在文本文件的每一行的末尾添加一些单词。如何使用 Bash 脚本执行此操作?

Example: add the word doneat the end of each line:

示例:done在每行末尾添加单词:

line1 abcdefg done
line2 abcdefg done
line3 abcdeft done

回答by anubhava

Use awk:

使用 awk:

awk 'NF{print 
sed -i.bak '!/[^[:blank:]]/s/$/ done/' inFile
" done"}' inFile

OR sed with inline flag:

或 sed 与内联标志:

set backup
g/^/ normal A done
normal ZZ

回答by Birei

Did I read vim?

我读过vim吗?

Content of script.vim:

内容script.vim

vim -S script.vim infile

Run it like:

像这样运行它:

#!/bin/bash

INFILE=
TMPFILE=/tmp/$INFILE.$$


while IFS= read -r; do
    echo "$REPLY done"; 
done <$INFILE >$TMPFILE ;

mv $TMPFILE $INFILE;

It will modify the file in-place creating a backup with ~suffix.

它将就地修改文件,创建带有~后缀的备份。

回答by imp25

If you want to do this in pure bash you could do:

如果你想在纯 bash 中做到这一点,你可以这样做:

bash append.sh file.txt

Which, if called append.shcan be called as such:

其中,如果调用append.sh可以这样调用:

line1 abcdefg 
line2 abcdefg 
line3 abcdeft 

Editedas per 1_CR's comments.

根据 1_CR 的评论进行编辑

回答by Debaditya

Perl way... same as that of the awk one liner

Perl方式......与awk one liner相同

Input

输入

  perl -lane 'print $F[0]," ",$F[1]," done"' Input 

Code

代码

 # cat append.txt
 line1 abcdefg
 line2 abcdefg
 line3 abcdeft

 # sed -i 's/$/done/g' append.txt

 # cat append.txt
 line1 abcdefg done
 line2 abcdefg done
 line3 abcdeft done

回答by Ranjithkumar T

sed is alway helpful for these kind of tasks,

sed 总是对这类任务有帮助,

 # cat sedcheck.sh
 #!/bin/bash
 if [ $# -eq 0 ]
    then
      echo "No input supplied"
    else
      sed -i 's/$/ ''/g' 
 fi


 # cat append.txt
 line1 abcdefg donedin
 line2 abcdefg donedin
 line3 abcdeft donedin

 # ./sedcheck.sh testing append.txt

 # cat append.txt
 line1 abcdefg donedin testing
 line2 abcdefg donedin testing
 line3 abcdeft donedin testing

or

或者

you can use the below script:

您可以使用以下脚本:

##代码##