Monday, April 29, 2024
6
rated 0 times [  6] [ 0]  / answers: 1 / hits: 4349  / 2 Years ago, sat, june 18, 2022, 12:54:47

I do have a bash script. I want to delete a specific string from a text file. I already found a command on the online but it seems it isn't that stable..


I've tried;


mv .admins .adminsold
sed -r "s#${MYFUNCTION}(,|$)##g" <.adminsold >.admins

My input file;


# Admin rule
[[rule]]
# Set your admin Group Ids here, ex: [ 13, 42 ]
groupid = [ 329, 2, 324, 156 ]
# And/Or your admin Client Uids here
useruid = []
# By default treat requests from localhost as admin
ip = [ "127.0.0.1", "::1" ]
"+" = "*"

Expected file;


# Admin rule
[[rule]]
# Set your admin Group Ids here, ex: [ 13, 42 ]
groupid = [ 329, 2, 156 ]
# And/Or your admin Client Uids here
useruid = []
# By default treat requests from localhost as admin
ip = [ "127.0.0.1", "::1" ]
"+" = "*"

More From » command-line

 Answers
3

If all you need is to remove 324,(i.e. exactly: one whitespace then 324 then one comma ,) from the file, then use:


sed 's/ 324,//' file

And to edit the file itself(i.e. overwrite the original file), use:


sed -i 's/ 324,//' file

Please see this answer for more info.




Things to consider from your example:



  • ? will make the previous character optional and you nead to escape it with a backslash ... e.g. to make the , optional use:


    sed 's/ 324,?//' file


  • If you need to match a literal /, you need to either escape it / or you can change the delimeter from the usual / to something else like @(or : or anything else) like so:


    sed 's@wxyz0123456789+/@@' file


  • If you want to apply the substitution only on lines that include groupid then specify /groupid/ as a condition before the substitution part like so:


    sed '/groupid/ s/ 324,//' file



[#320] Saturday, June 18, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
homerurhyth

Total Points: 338
Total Questions: 113
Total Answers: 105

Location: Moldova
Member since Sat, Aug 6, 2022
2 Years ago
;