[英]Linux SED script find the 1st line that match pattern and delete it
I want to create a sed command to find in a file the 1st line that matchs a pattern and the delete all that line or replace it all with some other text.我想创建一个 sed 命令以在文件中查找与模式匹配的第一行并删除所有该行或将其全部替换为其他文本。 I dont want to match all the line because the rule is to match part of it.
我不想匹配所有行,因为规则是匹配其中的一部分。
how can i do it with sed?我怎么能用 sed 做到这一点?
for instance:例如:
myline 1 is pretty
line 2 is ugly
myline 111 is nice
I want to delete the first line that contains "1 is"我想删除包含“1 is”的第一行
UPDATE: My line may have characters like "/" and "<"更新:我的行可能有像“/”和“<”这样的字符
Regards Fak问候法克
I tend to use awk
for more complicated tasks, it's a bit more powerful than sed
, having proper looping and selection constructs (expanded for readability, you can compress it back to one line if you wish):我倾向于将
awk
用于更复杂的任务,它比sed
更强大,具有适当的循环和选择结构(为提高可读性而扩展,如果您愿意,可以将其压缩回一行):
pax$ echo '
xyz
myline 1 is pretty
line 2 is ugly
myline 111 is nice' | awk '
/1 is/ {if (f) {print} else {f = 1}}
!/1 is/ {print}'
xyz
line 2 is ugly
myline 111 is nice
For any line not matching the pattern ( !/1 is/
), it just prints it.对于与模式不匹配的任何行(
!/1 is/
),它只会打印它。
For lines that do match the pattern, it prints them all if the flag f
is set (it's initially not set).对于与模式匹配的行,如果设置了标志
f
(最初未设置),它将全部打印出来。 When the flags not set and it encounters a matching line, it sets the flag and doesn't print it.当未设置标志并且遇到匹配行时,它会设置标志并且不打印它。 This basically deletes the first matching line as desired.
这基本上会根据需要删除第一条匹配行。
If you want to modify the first matching line rather than deleting it, you just insert code alongside the f = 1
to do that, something like:如果要修改第一个匹配行而不是删除它,只需在
f = 1
旁边插入代码即可,例如:
pax$ echo '
xyz
myline 1 is pretty
line 2 is ugly
myline 111 is nice' | awk '
/1 is/ {if (f) {print} else {f = 1;print "URK!!!"}}
!/1 is/ {print}'
xyz
URK!!!
line 2 is ugly
myline 111 is nice
To use a shell variable in awk
, you can use the -v
option to pass it in as a real awk
variable:要在
awk
中使用 shell 变量,您可以使用-v
选项将其作为真正的awk
变量传递:
pax$ export xyzvar=URK ; echo '
xyz
myline 1 is pretty
line 2 is ugly
myline 111 is nice' | awk -vmyvar=$xyzvar '
/1 is/ {if (f) {print} else {f = 1;print myvar}}
!/1 is/ {print}'
xyz
URK
line 2 is ugly
myline 111 is nice
You can accomplish it without sed.您可以在没有 sed 的情况下完成它。 Bash script:
Bash 脚本:
LINE=$(grep -n "$EXPR" "$FILE" |head -1 |cut -f1 -d:)
head -$(expr $LINE - 1 ) $FILE
tail +$(expr $LINE + 1 ) $FILE
Just declare $EXPR
and $FILE
.只需声明
$EXPR
和$FILE
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.