简体   繁体   English

sed使用shell脚本变量将选定的行删除到文件

[英]Sed remove selected line to file using shell script variable

I have shell script variable var="7,8,9" These are the line number use to delete to file using sed. 我有shell脚本变量var="7,8,9"这些是用于使用sed删除到文件的行号。

Here I tried: sed -i "$var"'d' test_file.txt 我在这里尝试过: sed -i "$var"'d' test_file.txt

But i got error `sed: -e expression #1, char 4: unknown command: ,' 但是我得到了错误`sed:-e expression#1,char 4:unknown command:,'

Is there any other way to remove the line? 还有其他删除线的方法吗?

sed command doesn't accept comma delimited line numbers. sed命令不接受逗号分隔的行号。

You can use this awk command that uses a bit if BASH string manipulation to form a regex with the given comma separated line numbers: 您可以使用以下awk命令,如果BASH字符串操作使用给定的逗号分隔的行号来形成一个正则表达式,它将使用一个位:

awk -v var="^(${var//,/|})$" 'NR !~ var' test_file.txt

This will set awk variable var as this regex: 这会将awk变量var设置为此正则表达式:

^(7|8|9)$

And then condition NR !~ var ensures that we print only those lines that don't match above regex. 然后条件NR !~ var确保我们仅打印那些与正则表达式不匹配的行。

For inline editing, if you gnu-awk with version > 4.0 then use: 对于内联编辑,如果您的gnu-awk版本> 4.0使用:

awk -i inplace -v var="^(${var//,/|})$" 'NR !~ var' test_file.txt

Or for older awk use: 或供较早的awk使用:

awk -v var="^(${var//,/|})$" 'NR !~ var' test_file.txt > $$.tmp && mv $$.tmp test_file.txt

I like sed, you were close to it. 我喜欢sed,您离它很近。 You just need to split each line number into a separate command. 您只需要将每个行号拆分为一个单独的命令。 How about this: 这个怎么样:

sed -e "$(echo 1,3,4 | tr ',' '\n' | while read N; do printf '%dd;' $N; done)"

这样做:

sed -i "`echo $var|sed 's/,/d;/g'`d;" file

Another option to consider would be ed , with printf '%s\\n' to put commands onto separate lines: 可以考虑的另一种选择是ed ,使用printf '%s\\n'将命令放在单独的行上:

lines=( 9 8 7 )
printf '%s\n' "${lines[@]/%/d}" w | ed -s file

The array lines contains the line numbers to be deleted; 数组lines包含要删除的行号; it's important to put these in descending order ! 重要的是将它们按降序排列 The expansion ${lines[@]/%/d} adds a d (delete) command to each line number and w writes to the file at the end. 扩展${lines[@]/%/d}在每个行号上添加d (删除)命令,并在最后写入w You can change this to ,p instead, to check the output before overwriting your file. 您可以将其更改为,p ,以在覆盖文件之前检查输出。

As an aside, for this example, you could also just use 7,9 as a single entry in the array. 7,9说一句,对于此示例,您也可以仅将7,9用作数组中的单个条目。

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

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