bash 删除文本文件的最后一行,而不是附加一行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17737583/
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
Removing the last line of a text file, instead of appending one?
提问by Paolo
In my Bash script, I write lines to a text file.
在我的 Bash 脚本中,我将行写入文本文件。
echo "string" > /folder/file.txt
The above example creates a new file and writes the string to that file.
上面的示例创建一个新文件并将字符串写入该文件。
echo "string" >> /folder/file.txt
The second example appends to the file, writing the string on a new line.
第二个示例追加到文件中,将字符串写入新行。
My question is… Is there a single command to remove the last line? If not, I guess I'll have to copy line by line into a temporary file, stop before the last line which is the one I want to remove, and then overwrite the old file with the new one (now without the last line). If that is the only solution, is there a way to find out how many lines there are in a text file? So I can do a loop stopping at "n - 1".
我的问题是......是否有一个命令可以删除最后一行?如果没有,我想我将不得不逐行复制到一个临时文件中,在我要删除的最后一行之前停止,然后用新文件覆盖旧文件(现在没有最后一行) . 如果这是唯一的解决方案,有没有办法找出文本文件中有多少行?所以我可以做一个在“n - 1”处停止的循环。
回答by Diego Torres Milano
Assuming you have GNU head:
假设你有 GNU 头:
$ head -n -1 file
prints all but the last (-1) line.
打印除最后 (-1) 行以外的所有内容。
回答by shellter
{ echo 1; echo 2 ; echo 3 ; } | sed '$d'
output
输出
1
2
or with a file
或者用一个文件
sed '$d' file > file.tmp && mv file.tmp file
OR with newer seds
或使用较新的 sed
sed -i '$d' file
the $char is taken as a range-address value meaning 'last-line-in-file'. You'll also see $used in regular expressions like '/at end of Line$/' (note the reg-exp delimiter pair of '/.../'). When used in a reg expression, $now means 'end-of-line'
所述$炭被作为一系列地址值意义“最后行式文件”。您还会看到$在正则表达式中使用,例如“/at end of Line$/”(注意 reg-exp 分隔符对“/.../”)。在 reg 表达式中使用时,$现在表示“行尾”
If you really want to know how many lines in a file (and assign it to a variable), do
如果您真的想知道文件中有多少行(并将其分配给变量),请执行
lineCount=$(/bin/wc -l <file)
echo $lineCount
IHTH
IHTH
回答by devnull
Here's how you might do it using awk:
以下是您可以使用的方法awk:
$ seq 1 5 | awk 'NR>1{print l}{l=$ seq 1 5 | perl -ne 'print if !eof'
1
2
3
4
}'
1
2
3
4
Using perl:
使用perl:
$ seq 1 5 | tac | sed '1d' | tac
1
2
3
4
Or if you prefer tic-tac-toe! (using tacand sed):
或者,如果您更喜欢井字游戏!(使用tac和sed):

