开发者

Some text replaccement issues. Please advise

开发者 https://www.devze.com 2023-03-13 18:04 出处:网络
I\'m new at bash scripting and I have a problem. I want to replace one line in a file with another one. This is my file:

I'm new at bash scripting and I have a problem. I want to replace one line in a file with another one. This is my file:

/home/iosub/linux/fis2 b7c839bf081421804e15c51d65a6f8fc -  
/home/iosub/linux/e212CIosub/doi 7edd241b1f05a9ea346c085b8c9e95c5 -    
/home/iosub/linux/e212CIosub/test2 7edd241b1f05a9ea346c085b8c9e95c5 -    
/home/iosub/linux/e212CIosub/xab ed4940ef42ec8f72fa8bdcf506a13f3d -    
/home/iosub/linux/e212CIosub/test1 8af599cfb361efb9cd4c2ad7b4c4e53a -    
/home/iosub/linux/e212CIosub开发者_开发问答/xaa 8cf57351b5fc952ec566ff865c6ed6bd -    
/home/iosub/linux/e212CIosub/test3 74420c2c4b90871894aa51be38d33f2c -

Without the blank lines. I want to replace a line with another one.

for example  /home/iosub/linux/e212CIosub/test1 8af599cfb361efb9cd4c2ad7b4c4e53a -
with         /home/iosub/linux/e212CIosub/test1 d2199e312ecd00ff5f9c12b7d54c97f1 -

I have /home/iosub/linux/e212CIosub/test1 in a variable and the new code in another variable.

I know that I must use sed. How can I do it?

I've tried a lot of combinations like:

sed "/$1/d"  cont > cont2;

where $1 is /home/iosub/linux/e212CIosub/test1

And after that I concatenate the new string to the file. This places the new line at the end of the file, it would be a good solution, if it would work . . . But it doesn't.It gives an error: sed: -e expression #1, char 5: extra characters after command

I've also tried the replacement method, but I didn't get any result.

Any solution would be good. Thank's


sed "s@$1@$var@g" -i filename

This will replace all occurences of $1 with $var in file filename inplace.


edit added '\' in front of @ chars for initial regex delimiters

when you have a '/' char in your search pattern, it breaks the use of that character ('/') as a reg-exp delimiter. Use a Regex delimiter that is NOT in your regex, i.e.

sed "\@$1@d" cont > cont2

Then continue with your processing.

But given your example, why don't you do something like

sed "s\@\($1\)(.*$)@\1 $2 -@" cont > cont2

This matches your value from $1, essentially deletes the text after your $1 value, and prints the $1 value followed by a space, your $2 value (d2....), a space and the ending '-' character.

Edit (Finally), I'll mention that some legacy Unix sed's (aix in particular) seem to not accept escaping the regex delimiter char (but I don't have access to a system to verify that now). In that case, you have to escape all of the any-and-all '/'s in your regex search pattern, like \/home\/iosub\/linux\/e212CIosub\/test1, yikes!

I hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消