简体   繁体   English

我想用sed命令编辑特定行(多行)

[英]I want to edit a specific lines (multiple) with sed command

I have a test file having around 20K lines in that file I want to change some specific string in specific lines I am getting the line number and strings to change.here I have a scenario where I want to change the one string to another in multiple lines. 我有一个测试文件,该文件中包含大约20K行,我想在特定行中更改某些特定的字符串,我要更改行号和字符串。在这里,我有一种情况是要将一个字符串更改为多个线。 I used earlier like 我以前喜欢

sed -i '12s/stringone/stringtwo/g'   filename

but in this case I have to run the multiple commands for same test like 但在这种情况下,我必须针对相同的测试运行多个命令,例如

sed -i '15s/stringone/stringtwo/g'   filename
sed -i '102s/stringone/stringtwo/g'   filename
sed -i '11232s/stringone/stringtwo/g'   filename

Than I tried below 比我下面尝试的

sed -i '12,15,102,11232/stringone/stringtwo/g' filename

but I am getting the error 但我得到了错误

sed: -e expression #1, char 5: unknown command: `,'

Please some one help me to achieve this. 请有人帮助我实现这一目标。

To get the functionality you're trying to get with GNU sed would be this in GNU awk: 要获得您尝试使用GNU sed获得的功能,请在GNU awk中进行以下操作:

awk -i inplace '
BEGIN {
    split("12 15 102 11232",tmp)
    for (i in tmp) lines[tmp[i]]
}
NR in lines { gsub(/stringone/,"stringtwo") }
' filename

Just like with a sed script, the above will fail when the strings contain regexp or backreference metacharacters. 就像sed脚本一样,当字符串包含regexp或向后引用元字符时,上述操作也会失败。 If that's an issue then with awk you can replace gsub() with index() and substr() for string literal operations (which are not supported by sed). 如果这是一个问题,那么使用awk可以将gsub()替换为index()和substr()进行字符串文字操作(sed不支持)。

You get the error because the N,M in sed is a range (from N to M ) and doesn't apply to a list of single line number. 之所以会出现错误,是因为sedN,M是一个范围(从NM ),并且不适用于单行号的列表。

An alternative is to use printf and sed : 一种替代方法是使用printfsed

sed -i "$(printf '%ds/stringone/stringtwo/g;' 12 15 102 11232)" filename

The printf statement is repeating the pattern Ns/stringone/stringtwo/g; printf语句正在重复模式Ns/stringone/stringtwo/g; for all numbers N in argument. 对于参数中的所有数字N

This might work for you (GNU sed): 这可能对您有用(GNU sed):

sed '12ba;15ba;102ba;11232ba;b;:a;s/pattern/replacement/' file

For each address, branch to a common place holder (in this case :a ) and do a substitution, otherwise break out of the sed cycle. 对于每个地址,分支到一个公共占位符(在这种情况下为:a )并进行替换,否则将退出sed循环。

If the addresses were in a file: 如果地址在文件中:

sed 's/.*/&ba/' fileOfAddresses | sed -f - -e 'b;:a;s/pattern/replacement/' file 

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

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