如何通过将行号作为变量传递来删除行? [英] How to delete a line by passing line number as variable?

查看:85
本文介绍了如何通过将行号作为变量传递来删除行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过将数字作为变量来删除文档的一行,就像这样:

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,我们创建一个名为noawk变量.使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆