Linux

如果單詞以特定字元串結尾,如何添加字元串

  • May 21, 2018

我們要更新以下文件,如果 MACHINE_NAME 以**“.localdomain”**結尾,則需要在單詞的開頭添加字元串 linux

每個 MACHINE_NAME 都帶有單括號’……'

更改前的文件範例

['server_primary01.localdomain', 'server_primary02.localdomain', 'server_primary03.localdomain']
EDIT_HOSTS.append( {'HOST' : 'Client0{0}.localdomain'.format(count+1)} )
EDIT_HOSTS.append( {'HOST' : 'Client{0}.localdomain'.format(count+1)} )
EDIT_HOSTS.append( {'HOST' : 'Client0{0}.localdomain'.format(count+1)} )
EDIT_HOSTS.append( {'HOST' : 'Client{0}.localdomain'.format(count+1)} )

改變後的例子

       ['linuxserver_primary01.localdomain', 'linuxserver_primary02.localdomain', 'linuxserver_primary03.localdomain']
       EDIT_HOSTS.append( {'HOST' : 'linuxClient0{0}.localdomain'.format(count+1)} )
       EDIT_HOSTS.append( {'HOST' : 'linuxClient{0}.localdomain'.format(count+1)} )
       EDIT_HOSTS.append( {'HOST' : 'linuxClient0{0}.localdomain'.format(count+1)} )
       EDIT_HOSTS.append( {'HOST' : 'linuxClient{0}.localdomain'.format(count+1)} )

**sed**解決方案:

sed -E "s/[^[:space:]']+\.localdomain/linux&/g" file

樣本輸出:

['linuxserver_primary01.localdomain', 'linuxserver_primary02.localdomain', 'linuxserver_primary03.localdomain']
EDIT_HOSTS.append( {'HOST' : 'linuxClient0{0}.localdomain'.format(count+1)} )
EDIT_HOSTS.append( {'HOST' : 'linuxClient{0}.localdomain'.format(count+1)} )
EDIT_HOSTS.append( {'HOST' : 'linuxClient0{0}.localdomain'.format(count+1)} )
EDIT_HOSTS.append( {'HOST' : 'linuxClient{0}.localdomain'.format(count+1)} )

引用自:https://unix.stackexchange.com/questions/445129