简体   繁体   English

仅当bash中存在头文件时,才如何从文件中删除头文件?

[英]How to remove the header from a file only if exist in bash?

I have this sample file. 我有这个样本文件。 I want to remove the first line (header) of this file only when it (header) exist using bash. 我只想使用bash删除该文件的第一行(标题)。

id name job_id
1 john 25
2 adam 45
3 paul 75

You can do it in one operation with sed using the -i option (assuming your version of sed supports it — not all do). 您可以使用-i选项在sed中执行一项操作(假设您的sed版本支持它-并非全部都支持)。 For example: 例如:

sed -i.bak -e '1{/^id name job_id/d;}' file

This takes line 1 of the file and applies the commands in the braces to it. 这将占用文件的第1行,并将大括号中的命令应用于该文件。 The braces search for the pattern shown and delete the line. 大括号搜索显示的模式并删除该行。 If the first line doesn't match, it isn't deleted. 如果第一行不匹配,则不会删除。 Other lines are left untouched. 其他线路保持不变。

The semicolon and backup suffix are necessary with Mac OS X sed ; Mac OS X sed必须使用分号和备份后缀; with GNU sed , you could omit either or both. 使用GNU sed ,您可以省略其中一个或两个。

你也可以使用awk来做到这一点:

awk 'NR!=1||$0!="id name job_id" {print $0}' file > newfile
filename='myfile'
[[ $(head -n 1 -- "$filename") == 'id name job_id' ]] && sed -i '1d' -- "$filename"
if head -1 original.txt | grep -Fxq 'id name job_id'
then tail -n+2 original.txt > newdoc.txt
fi

EDIT: Only checks first line and prints rest in a new file if the header exists. 编辑:仅检查第一行,如果标头存在,则将其余部分打印在新文件中。 If not, the original is unchanged. 如果不是,则原件不变。

sed '/id name job_id/d' fileName

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

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