Chinaunix
标题:
如何去掉文本最后一行的最后一个字符
[打印本页]
作者:
我是一个小啊小菜鸟
时间:
2016-04-27 09:12
标题:
如何去掉文本最后一行的最后一个字符
请大神帮忙下,最近接触文本处理遇见了问题
{"X":40.172819,"Y":116.383621,"Z":.0117,"T":"2016-04-26 16:00:00"},
{"X":39.760256,"Y":116.305211,"Z":.2923,"T":"2016-04-26 16:00:00"},
{"X":39.959291,"Y":116.32090099999999,"Z":.3288,"T":"2016-04-26 16:00:00"},
{"X":40.019980999999994,"Y":116.339131,"Z":.2475,"T":"2016-04-26 16:00:00"},
{"X":39.983142,"Y":116.303713,"Z":1.155,"T":"2016-04-26 16:00:00"},
现在我想把最后一行结尾的逗号(,)去掉,sed该怎么写啊
作者:
haooooaaa
时间:
2016-04-27 09:18
sed '$s/,$//'
复制代码
作者:
mswsg
时间:
2016-04-27 09:25
python remove_last.py --input your_input_file > out.txt
将下面的代码保存为remove_last.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'shengwei ma'
__author_email__ = 'shengweima@icloud.com'
import sys
import getopt
input_file = ""
try:
opts, args = getopt.getopt(sys.argv[1:], "h", ["input="])
except getopt.GetoptError as err:
print(str(err))
for op, value in opts:
if op == "--input":
input_file = value
elif op == "-h":
print("python remove_last.py --input your_input_file > out.txt")
sys.exit()
with open(input_file, 'r') as f:
lines = f.read().strip()
print lines[:-1]
复制代码
作者:
我是一个小啊小菜鸟
时间:
2016-04-27 09:26
谢谢
回复
2#
haooooaaa
作者:
我是一个小啊小菜鸟
时间:
2016-04-27 09:27
谢谢,没sed好用啊 ,您这个很强大,但是我看不懂
回复
3#
mswsg
作者:
mswsg
时间:
2016-04-27 09:30
没事,你这种单个文件的当然大材小用了。
回复
5#
我是一个小啊小菜鸟
作者:
sync_1521
时间:
2016-04-27 09:33
awk '{sub(",$","")}1' file
作者:
elu_ligao
时间:
2016-04-27 09:51
回复
7#
sync_1521
这个会把所有以, 结尾的, 都去掉吧, 不是最后一行的, 哦
作者:
sync_1521
时间:
2016-04-27 10:43
回复
8#
elu_ligao
没细看。。想当然了
awk '{if(s){print s};s=$0}END{sub(",$","");print}' file
awk 'NR==FNR{n=NR;next}FNR==n{sub(",$","")}1' file file
复制代码
作者:
jcdiy0601
时间:
2016-04-28 10:32
sed 's/.$//' file
{"X":40.172819,"Y":116.383621,"Z":.0117,"T":"2016-04-26 16:00:00"}
{"X":39.760256,"Y":116.305211,"Z":.2923,"T":"2016-04-26 16:00:00"}
{"X":39.959291,"Y":116.32090099999999,"Z":.3288,"T":"2016-04-26 16:00:00"}
{"X":40.019980999999994,"Y":116.339131,"Z":.2475,"T":"2016-04-26 16:00:00"}
{"X":39.983142,"Y":116.303713,"Z":1.155,"T":"2016-04-26 16:00:00"}
awk '{sub(/.$/,"")}1' file
{"X":40.172819,"Y":116.383621,"Z":.0117,"T":"2016-04-26 16:00:00"}
{"X":39.760256,"Y":116.305211,"Z":.2923,"T":"2016-04-26 16:00:00"}
{"X":39.959291,"Y":116.32090099999999,"Z":.3288,"T":"2016-04-26 16:00:00"}
{"X":40.019980999999994,"Y":116.339131,"Z":.2475,"T":"2016-04-26 16:00:00"}
{"X":39.983142,"Y":116.303713,"Z":1.155,"T":"2016-04-26 16:00:00"}
作者:
sunzhiguolu
时间:
2016-04-28 12:50
perl -nle '{if($.>1){print $s}$s=$_}END{print substr($s,0,-1)}' file
复制代码
作者:
tolilong
时间:
2016-04-28 13:37
awk -F"}" '{print $1"}"}' filename
作者:
xdsnet
时间:
2016-04-28 14:25
楼主是要最后一行的最后一个逗号,而不是每行的逗号啊。
作者:
龙神add
时间:
2016-05-01 23:57
sed 's/,$//g' filename
比较简单
作者:
龙神add
时间:
2016-05-01 23:57
这是python?
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2