sed 找出含有某個字串的行 注釋掉

2022-06-18 08:51:14 字數 1182 閱讀 7249

1、原始檔例子

[root@node1 ~]# cat /etc/fstab

## /etc/fstab

# created by anaconda on mon mar

118:32:15

2021

## accessible filesystems, by reference, are maintained under

'/dev/disk

'# see

man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for

more

info#0

uuid=3fa2b010-61bc-480e-bd49-cb7bee120fe3 /boot xfs defaults 000

[root@node1 ~]#

2、cp乙個檔案出來  測試修改  fs.txt

sed -i '

/swap/s/^/#/g

' fs.txt

3、diff看一下  ok了

[root@node1 ~]# diff fs.txt /etc/fstab

11c11

0---

0[root@node1 ~]# cat /etc/fstab

4、如果要冪等執行 得判斷是否被注釋過了  如果注釋過了 則不執行  不然就執行 然後再判斷  這個適合用 until 命令

until

grep swap fs.txt |grep"#

" >/dev/null;do

echo

"disable swap

" && sed -i '

/swap/s/^/#/g

' fs.txt;done

5、測試ok  換成實際環境 就是下面的  可以重複執行  

until

grep swap /etc/fstab |grep"#

" >/dev/null;do

echo

"disable swap

" && sed -i '

/swap/s/^/#/g

' /etc/fstab;done

當前含有某個字串的某個檔案 grep

grep rn hello,world find maxdepth 1 name f xargs grep nr color auto best test acc 表示當前目錄所有檔案,也可以是某個檔名 r 是遞迴查詢 n 是顯示行號 r 查詢所有檔案包含子目錄 i 忽略大小寫下面是一些有意思的命令...

當前含有某個字串的某個檔案 grep

grep rn hello,world 輸出檔案中不包含match的行 grep v c words val full.csv processed 12 13.json find maxdepth 1 name f xargs grep nr color auto best test acc 表示當...

判斷某個字串中是否含有特殊字元

有時候,我們要對文字框中輸入的字元進行判斷,是否含有特殊字元。例如,在使用者註冊時如果只允許使用者名為數字和字母組成,我們就可以使用以下定義的函式進行判斷 str 要被判斷的字串 compare 要判斷是否含有的字元集合的字串 belongornot 布林值,為true表示判斷str中的字元是否都包...