Thursday, May 2, 2024
 Popular · Latest · Hot · Upcoming
4
rated 0 times [  4] [ 0]  / answers: 1 / hits: 10197  / 1 Year ago, mon, december 26, 2022, 5:01:32

I want to put in sudo gedit /etc/sysctl.conf the one line vm.swappiness=10 which I sometimes change.



By default this line doesnt exist so I use echo "vm.swappiness=10" | sudo tee -a /etc/sysctl.conf.



If I would always be putting the same exact line vm.swappiness=10, then in case I want to replace I could use sudo sed -i 's/vm.swappiness=10/vm.swappiness=1/g' /etc/sysctl.conf But since there could be vm.swappiness=12 or something else, I want--with just a single command--to find if, in /etc/sysctl.conf, there exists line starting vm.swappiness=. Then if it does exist I want to remove the whole line (then by appending && echo "vm.swappiness=1" | sudo tee -a /etc/sysctl.conf to that command, it would also subsequently add the new configuration line that I want to the end.



But again since there could be a lot of different parameters in one line, it wouldn't be good to delete it all, but would be better to change only the number (to the immediate right of vm.swappiness=).



What you think? Would it be better to search for vm.swappiness=x(x(x)) with 1 to 3 numbers (of course, 100 also exists...), replace if it's there (by putting it into a variable and using a command like `sudo sed -i 's/$oldline/$newline/g'), and if not then just append vm.swappiness=10?


More From » bash

 Answers
2

You can use



sed 's/vm.swappiness=[0-9]*/vm.swappiness=1/g' /etc/sysctl.conf


If you don't mind how many digits your number has.



If you want a maximum of 3 digits, you need extended (modern) regular expressions rather than basic regular expressions (BRE's). You then need to provide the -E parameter



sed -E 's/vm.swappiness=[0-9]{1,3}/vm.swappiness=1/g' /etc/sysctl.conf

[#42210] Monday, December 26, 2022, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
freezidepu

Total Points: 394
Total Questions: 105
Total Answers: 118

Location: Libya
Member since Mon, Dec 7, 2020
3 Years ago
;