如何通过将行号作为变量传递来删除行? [英] How to delete a line by passing line number as variable?
问题描述
我想通过将数字作为变量来删除文档的一行,就像这样:
I want to delete a line of a document by passing the number as variable, like so:
ERR=`set of bash commands` ; sed '${ERR}d' file
但是上述单引号中的sed命令不起作用.那么如何完成这项任务呢?
However the above sed command in single quotes does not work. How to achieve this task then?
推荐答案
对于给定文件
$ cat file
1
2
3
4
5
6
7
8
9
10
和包含行号(如
$ ERR=5
使用sed
:
使用双引号允许变量进行插值.注意使用花括号允许sed
区分变量和d
标志.在输出行号5不再是打印机.
Using sed
:
Use double quote to allow the variable to interpolate. Notice the use of curly braces to allow sed
to differentiate between variable and d
flag. In the output line number 5 is no longer printer.
$ sed "${ERR}d" file
1
2
3
4
6
7
8
9
10
使用awk
:
NR
存储给定文件的行号.使用-v
选项将shell变量传递给awk
,我们创建一个名为no
的awk
变量.使用NR
不等于我们的awk
变量的条件,我们告诉awk
打印除不想打印的行号以外的所有内容.
Using awk
:
NR
stores the line number for a given file. Passing the shell variable to awk
using -v
option we create an awk
variable called no
. Using the condition where NR
is not equal to our awk
variable we tell awk
to print everything except the line number we don't want to print.
$ awk -v no="$ERR" 'NR!=no' file
1
2
3
4
6
7
8
9
10
这篇关于如何通过将行号作为变量传递来删除行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!