我想使用命令来注释和取消注释/etc/fstab 中的 swap
分区,而不会对已经注释的行产生副作用。
用例 1) 示例 fstab:
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point> <type> <options> <dump> <pass>
# / was on /dev/sda6 during installation
UUID=97166a83-2932-4a8b-862a-68aa71d4e166 / ext4 errors=remount-ro 0 1
# swap was on /dev/sda5 during installation
UUID=b95babcf-2d8d-412d-a15d-c8f9de651ee8 none swap sw 0 0
我设法使用以下命令对其进行注释/取消注释:
sudo sed -i.bak -r 's/(.+ swap .+)/#\1/' /etc/fstab
sudo sed -i '/^#.* swap /s/^#//' /etc/fstab
问题在于,安装期间 swap was on/dev/sda5
行也被注释/取消注释,如果取消注释两次,可能会导致文档失去完整性,从而导致:
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point> <type> <options> <dump> <pass>
# / was on /dev/sda6 during installation
UUID=97166a83-2932-4a8b-862a-68aa71d4e166 / ext4 errors=remount-ro 0 1
swap was on /dev/sda5 during installation
UUID=b95babcf-2d8d-412d-a15d-c8f9de651ee8 none swap sw 0 0
更新:
用例 2)某些交换分区没有 UUID:
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point> <type> <options> <dump> <pass>
# / was on /dev/sda2 during installation
UUID=112aa94b-3c82-4a90-9600-e3e45dc820de / ext4 errors=remount-ro 0 1
# /home was on /dev/sda3 during installation
UUID=24ec038a-a164-4d32-809a-5a5552c009e9 /home ext4 defaults 0 2
/swapfile none swap sw 0 0
我如何创建一个 sed 表达式来发表这些评论?
最佳答案
你可以试试这个:
sudo sed -i 's/.* none.* swap.* sw.*/#&/' /etc/fstab
sudo sed -i '/.* none.* swap.* sw.*/s/^#//' /etc/fstab
关于regex - 如何使用 sed 正确注释和取消注释 fstab?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57173865/