简体   繁体   English

如何使用sed删除csv文件的第一行和最后一行

[英]how to remove both first and last line of csv file using sed

I can remove the first line of csv file's starting with myfile and merge them using: 我可以删除以myfile开头的csv文件的第一行,并使用以下命令合并它们:

sed 1d myfile*.csv > myfile_merged.csv

I'd like to also remove the last line of the csv files. 我还想删除csv文件的最后一行。

I've tried: 我试过了:

sed 1d -i '$d' myfile*.csv > myfile_merged.csv

But get the error: 但是得到错误:

sed: can't read $d: No such file or directory

Problem is this command: 问题是此命令:

sed 1d -i '$d' myfile*.csv > myfile_merged.csv

You need not have an argument after -i ( inline replacement ) in sed otherwise it is treated as a SUFFIX to create a backup for inline replacement. sed -i内联替换 )后面不需要参数,否则它将被视为SUFFIX以创建用于内联替换的备份。

What you need is this gnu sed command: 您需要的是以下gnu sed命令:

sed -i '1d;$d' myfile*.csv

This will remove 1st and last line in each of the matched file and save it in place. 这将删除每个匹配文件中的第一行和最后一行,并将其保存到位。

What you're probably trying to do is: 您可能想做的是:

sed -e '1d' -e '$d' myfile*.csv > merged.csv

But this won't work, because it tells sed to remove the first and last line of ALL files, rather than EACH file. 但这是行不通的,因为它告诉sed删除所有文件的第一行和最后一行,而不是EACH文件。 In other words, you'll strip the first line of the first file, and the last line of the last file ... and that's it. 换句话说,您将删除第一个文件的第一行,最后一个文件的最后一行...就是这样。

To process each file individually, you probably need to process each file .. individually. 要单独处理每个文件,您可能需要分别处理每个文件..。 :) :)

for f in myfile*.csv
    sed -e '1d;$d' "$f"
done > merged.csv

Note that while this will run in bash, it's also POSIX compatible (both the shell and sed parts). 请注意,尽管这将在bash中运行,但它也与POSIX兼容(外壳和sed部件)。 And it does not care whether your input is CSV or any other format, as long as it can be parsed line by line using sed. 只要输入可以使用sed逐行解析,它也不关心您的输入是CSV还是其他格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM