添加到每个文件中的行尾

时间:2015-02-13 18:56:25

标签: sed

我有25,000个.txt文件,它们都统一遵循这种模式:

String found only at the start of line 1 in every file :Variable text with no pattern
String found only at the start of line 2 in every file :(Variable text with no pattern
String found only at the start of line 3 in every file :(Variable text with no pattern
String found only at the start of line 4 in every file :(Variable text with no pattern
String found only at the start of line 5 in every file :[Variable text with no pattern

任何人都可以告诉我如何在第1行的末尾添加一个空的空格,在第2,3和4行的末尾添加一个右括号括号,并在末尾添加一个封闭的副本括号当前目录中的每个文件的第5行和sed的所有子目录?我现在是通过终端批量编辑文本文件的新手,并且似乎无法在几小时内寻找解决方案时弄清楚如何在修改这些文件的内容时执行最后一步。

感谢任何想法,解决方案或有用的链接 彼得伍德 (使用Debian 7)

2 个答案:

答案 0 :(得分:0)

以下内容将请求的字符添加到请求行的末尾。 (我不确定"复制括号"是什么,所以我使用了]):

$ sed '1s/$/ /; 2,4s/$/)/; 5s/$/\]/' file.txt
String found only at the start of line 1 in every file :Variable text with no pattern 
String found only at the start of line 2 in every file :(Variable text with no pattern)
String found only at the start of line 3 in every file :(Variable text with no pattern)
String found only at the start of line 4 in every file :(Variable text with no pattern)
String found only at the start of line 5 in every file :[Variable text with no pattern]

如何运作

  • 1s/$/ /

    1告诉sed仅将此替换应用于行. $ matches at the end of a line. The s`命令会在行尾添加一个空格。

    替换命令的格式为s/old/new/。它们与old文本匹配,并将其替换为new。在我们的例子中,我们希望在一行的末尾匹配,表示为$,并在那里放置一个空格。

  • 2,4s/$/)/

    2,4告诉sed仅将此替换应用于2到4范围内的行。它会在行尾添加)

    < / LI>
  • 5s/$/\]/

    5告诉sed仅将此替换应用于第5行。它会在行尾添加]。由于]是sed-active,因此必须对其进行转义。

将其应用于您的所有文件

要更改所有文件,使用扩展名.bak制作备份副本,请使用:

sed -i.bak '1s/$/ /; 2,4s/$/)/; 5s/$/\]/' *.txt

答案 1 :(得分:0)

以下是awk版本:

awk 'NR==1 {$0=$0" "} NR>1 && NR<5 {$0=$0")"} NR==5 {$0=$0"]"} 1' files*
String found only at the start of line 1 in every file :Variable text with no pattern
String found only at the start of line 2 in every file :(Variable text with no pattern)
String found only at the start of line 3 in every file :(Variable text with no pattern)
String found only at the start of line 4 in every file :(Variable text with no pattern)
String found only at the start of line 5 in every file :[Variable text with no pattern]

它只是使用NR(行号)逐行测试并添加所需的内容 最后一个1用于打印修改后的行。