如何删除文件中某些行中的特定字符?

How can I remove specific characters in certain lines in a file?

如何从第 3 行开始的第 5 列到第 7 列剪切字符?

我正在尝试使用 sed/cut。

例如,如果我有

this is amazing1 this is amazing11
this is amazing2 this is amazing21
this is amazing3 this is amazing31
this is amazing4 this is amazing41
this is amazing5 this is amazing51
this is amazing6 this is amazing61
this is amazing7 this is amazing71

输出应如下所示:

this is amazing1 this is amazing11
this is amazing2 this is amazing21
this amazing3 this is amazing31
this amazing4 this is amazing41
this amazing5 this is amazing51
this amazing6 this is amazing61
this amazing7 this is amazing71

第 3 行及以后的字符 is 被删除。

我只是为了清晰、可移植性等原因而使用 awk:

$ awk 'NR>2{[=10=]=substr([=10=],1,4) substr([=10=],8)} 1' file
this is amazing1 this is amazing11
this is amazing2 this is amazing21
this amazing3 this is amazing31
this amazing4 this is amazing41
this amazing5 this is amazing51
this amazing6 this is amazing61
this amazing7 this is amazing71

或使用用您问题中的值填充的变量:

$ awk -v n=3 -v beg=5 -v end=7 'NR>=n{[=11=]=substr([=11=],1,beg-1) substr([=11=],end+1)} 1' file
this is amazing1 this is amazing11
this is amazing2 this is amazing21
this amazing3 this is amazing31
this amazing4 this is amazing41
this amazing5 this is amazing51
this amazing6 this is amazing61
this amazing7 this is amazing71

分两步:

head -n2 infile; tail -n+3 infile | cut --complement -c5-7

第一个命令打印前两行未修改;第二个命令将以第三个命令开始的行传输到 cut,其中字符 5 到 7 被删除(需要 GNU cut)。

如果您需要对输出执行某些操作,例如将其存储在文件中,则必须在重定向之前对这些命令进行分组:

{
    head -n2 infile
    tail -n+3 infile | cut --complement -c5-7
} > outfile
sed -E '3,$s/(....)...//' file

如果你想使用sed:

sed '1,2!s/^\(\w*\)\s*\w*\(.*\)$//' file

详情

  • 1,2!s - 不要在第 1 行和第 2 行进行替换。
  • /^\(\w*\)\s*\w*\(.*\)$/ - 匹配模式。
  • // - 恢复1和2组。
  • file - 您的输入文件。