我有几个具有不同行号的文本文件,我必须在所有这些文件中删除倒数第三行。这是一个示例文件:
bear
horse
window
potato
berry
cup
Run Code Online (Sandbox Code Playgroud)
此文件的预期结果:
bear
horse
window
berry
cup
Run Code Online (Sandbox Code Playgroud)
我们可以删除文件的倒数第三行吗
?不基于任何字符串/模式。
湾 仅基于它必须是倒数第三行的条件
我对如何从最后一行开始索引我的文件有疑问。我已经从倒数第二行的另一个 SO 问题中尝试过这个:
> sed -i 'N;$!P;D' output1.txt
Run Code Online (Sandbox Code Playgroud)
使用tac
+awk
解决方案,请您尝试以下操作。只需将line
变量设置为awk
要跳过的行(从底部)。
tac Input_file | awk -v line="3" 'line==FNR{next} 1' | tac
Run Code Online (Sandbox Code Playgroud)
说明:使用tac
将读取 Input_file 反向(从底行到第一行),将其输出传递给awk
命令,然后检查条件是否行等于行(我们要跳过)然后不打印该行,1 将打印其他线路。
第二种解决方案:使用awk
+wc
解决方案,请尝试以下操作。
awk -v lines="$(wc -l < Input_file)" -v skipLine="3" 'FNR!=(lines-skipLine+1)' Input_file
Run Code Online (Sandbox Code Playgroud)
说明:awk
在此处启动程序并创建一个变量lines
,该变量具有 Input_file 中存在的总行数。变量skipLine
具有我们想要从 Input_file 底部跳过的行号。然后在主程序检查条件,如果当前行不等于lines-skipLine+1
然后打印行。
第三个解决方案:根据 Ed sir 的评论添加解决方案。
awk -v line=3 '{a[NR]=$0} END{for (i=1;i<=NR;i++) if (i != (NR-line)) print a[i]}' Input_file
Run Code Online (Sandbox Code Playgroud)
说明:为第三个解决方案添加详细说明。
awk -v line=3 ' ##Starting awk program from here, setting awk variable line to 3(line which OP wants to skip from bottom)
{
a[NR]=$0 ##Creating array a with index of NR and value is current line.
}
END{ ##Starting END block of this program from here.
for(i=1;i<=NR;i++){ ##Starting for loop till value of NR here.
if(i != (NR-line)){ ##Checking condition if i is NOT equal to NR-line then do following.
print a[i] ##Printing a with index i here.
}
}
}
' Input_file ##Mentioning Input_file name here.
Run Code Online (Sandbox Code Playgroud)
和 ed
ed -s ip.txt <<< $'$-2d\nw'
# thanks Shawn for a more portable solution
printf '%s\n' '$-2d' w | ed -s ip.txt
Run Code Online (Sandbox Code Playgroud)
这将进行就地编辑。$
指的是最后一行,您可以指定一个负的相对值。所以,$-2
将参考最后但第二行。w
命令将写入更改。
有关更多详细信息,请参阅ed:行寻址。