【问题标题】:How to delete the last nth characters from the nth line with sed?如何用sed从第n行删除最后n个字符?
【发布时间】:2020-04-13 03:53:04
【问题描述】:

Ubuntu 16.04
重击 4.4

我想删除第 n 行的最后 n 个字符。这是一个简单的文件,每行最后 4 个字符是数字 4。

root@0o0o0o0o0 ~/.ssh # cat remove.txt
00000000004444
55555555555555555555555554444
222222222222222224444
000033334444
111114444

要删除每行的最后 4 个字符,我可以执行 sed -i 's/....$//' remove.txt

root@0o0o0o0o0 ~/.ssh # sed -i 's/....$//' remove.txt
root@0o0o0o0o0 ~/.ssh # cat remove.txt
0000000000
5555555555555555555555555
22222222222222222
00003333
11111

但是,如果我想从第 4 行删除最后 4 个字符,删除 3,使文件看起来像这样:

0000000000
5555555555555555555555555
22222222222222222
0000
11111

【问题讨论】:

    标签: awk sed


    【解决方案1】:

    使用 GNU sed:

    sed -i 's/....$//; 4s/....$//' file
    

    4s/....$// 将搜索和替换限制在第 4 行。


    请参阅:man sedinfo sed

    【讨论】:

    • sed -Ei 's/.{4}$//; 4s/.{4}$//' file,如果有很多字符要删除。由于命令较长,因此在这里没有任何意义。
    • @Freddy 为了让我能更清楚地理解,我现在想删除第 30 行的最后 3 个字符。我应该选择 2 个不同的数字。
    • s前面的第一个数字是行号,{...}里面的数字是$末尾要替换的字符数。
    • 请注意,一行必须有足够的字符才能工作,否则不会删除任何内容。如果不能保证,那么您可以在 Cyrus 的解决方案中将每个 . 替换为 .\?,或者在 Freddy 的解决方案中将每个 {4} 替换为 {0,4}
    【解决方案2】:

    请您尝试关注awk。用 GNU awk 编写和测试。

    awk -v line="4" -v nofChar="4" '
    {
      sub(".{"nofChar"}$","")
    }
    FNR==line{
      sub(".{"nofChar"}$","")
    }
    1
    '  Input_file
    

    详细解释:

    awk -v line="4" -v nofChar="4" '   ##Starting awk program and setting line variable value, nofChar variable value here.
    {
      sub(".{"nofChar"}$","")          ##Substituting last nofChar number of characters at last of the each line here.
    }
    FNR==line{                         ##Checking if this is same line which OP wants to do 2nd time substitution.
      sub(".{"nofChar"}$","")          ##Substituting last nofChar number of characters at last of the each line here.
    }
    1                                  ##Mentioning 1 will print edited/non-edited line.
    '  Input_file                      ##Mentioning Input_file name here.
    


    第二个解决方案:如果所有行中的字符数与特定行不同,请尝试以下操作。必须更改名为nofUsualChar 的变量值。

    awk -v line="4" -v nofChar="4" -v nofUsualChar="4" '
    {
      sub(".{"nofUsualChar"}$","")
    }
    FNR==line{
      sub(".{"nofChar"}$","")
    }
    1
    '  Input_file
    

    【讨论】:

      猜你喜欢
      • 2015-12-09
      • 2019-03-20
      • 1970-01-01
      • 2019-07-05
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 2012-11-03
      相关资源
      最近更新 更多