Linux - 从给定行号删除所有行
Linux - Delete all lines from a given line number
我正在尝试使用 sed 从提供的行号中删除文件的内容。问题是 sed 不接受我提供给它的变量
line_num=$(grep -n "debited" file.csv | sed -n '2 s/:.*//p') && sed -i.bak "$line_num,$d" file.csv
想法是从文件中删除所有行,包括第二次出现的模式。
我对 sed
并不固执。 Awk
& perl
也可以。
您似乎想在第二次显示模式 (debited
) 后删除文件的其余部分,包括该行。
然后可以 truncate it, ising tell 读取到该行的长度
perl -e'while (<>) {
if ( ($cnt += /debited/) == 2 ) { truncate $ARGV, $len; exit }
$len = tell;
}' file
这里是$ARGV variable has the "current" file (when reading from <>)。根据您的上下文,随意引入一个带有模式而不是文字 (debited
) 的变量。
这可以在一个小脚本中看起来更好,但似乎问题中需要一个命令行程序(“one-liner”)。
你正在做很多不必要的步骤,这会做你想做的。
$ awk '/debited/{c++} c==2{exit}1' file
删除第二次出现的模式及其后的所有内容。
替换原文件(并创建备份)
$ awk ... file > t && mv -b --suffix=.bak t file
我总是建议 ed
ed 尝试使用 sed
编辑文件;一个从一开始就打算使用文件而不是行流的程序对于大多数任务来说效果更好。
The idea is to delete all lines from a file after & including the second occurence[sic] of the pattern
示例:
$ cat demo.txt
a
b
c
debited 12
d
e
debited 14
f
g
h
$ printf "%s\n" '/debited/;//,$d' w | ed -s demo.txt
$ cat demo.txt
a
b
c
debited 12
d
e
ed
命令/pattern/;//,$d
首先将当前行光标设置为匹配基本正则表达式模式的第一个,然后将其移动到模式的下一个匹配项并删除从那里到文件末尾的所有内容。然后 w
将更改后的文件写回磁盘。
我正在尝试使用 sed 从提供的行号中删除文件的内容。问题是 sed 不接受我提供给它的变量
line_num=$(grep -n "debited" file.csv | sed -n '2 s/:.*//p') && sed -i.bak "$line_num,$d" file.csv
想法是从文件中删除所有行,包括第二次出现的模式。
我对 sed
并不固执。 Awk
& perl
也可以。
您似乎想在第二次显示模式 (debited
) 后删除文件的其余部分,包括该行。
然后可以 truncate it, ising tell 读取到该行的长度
perl -e'while (<>) {
if ( ($cnt += /debited/) == 2 ) { truncate $ARGV, $len; exit }
$len = tell;
}' file
这里是$ARGV variable has the "current" file (when reading from <>)。根据您的上下文,随意引入一个带有模式而不是文字 (debited
) 的变量。
这可以在一个小脚本中看起来更好,但似乎问题中需要一个命令行程序(“one-liner”)。
你正在做很多不必要的步骤,这会做你想做的。
$ awk '/debited/{c++} c==2{exit}1' file
删除第二次出现的模式及其后的所有内容。
替换原文件(并创建备份)
$ awk ... file > t && mv -b --suffix=.bak t file
我总是建议 ed
ed 尝试使用 sed
编辑文件;一个从一开始就打算使用文件而不是行流的程序对于大多数任务来说效果更好。
The idea is to delete all lines from a file after & including the second occurence[sic] of the pattern
示例:
$ cat demo.txt
a
b
c
debited 12
d
e
debited 14
f
g
h
$ printf "%s\n" '/debited/;//,$d' w | ed -s demo.txt
$ cat demo.txt
a
b
c
debited 12
d
e
ed
命令/pattern/;//,$d
首先将当前行光标设置为匹配基本正则表达式模式的第一个,然后将其移动到模式的下一个匹配项并删除从那里到文件末尾的所有内容。然后 w
将更改后的文件写回磁盘。