Linux

如何通過 vi 或任何其他工具替換模式後的單詞/數字,但僅替換一個單詞,而不是後面的單詞

  • January 29, 2021

我想在多個腳本中將埠號更改為 0,但我希望埠 0 之後的文本保持不變。有沒有辦法做到這一點。通過 vi,我可以更改模式,但不能更改埠號,因為它們都是唯一的。謝謝!

local-ip 159.105.100.40 port 5510 remote-ip 152.16.142.104 port 3868 

sed很簡單:

$ foo="local-ip 159.105.100.40 port 5510 remote-ip 152.16.142.104 port 3868"
$ echo "$foo" | sed 's/port [0-9]\{1,5\}/port 0/g'
local-ip 159.105.100.40 port 0 remote-ip 152.16.142.104 port 0

所以

# let's suppose that all your scripts are in the same directory
# and have the extension .sh
for file in *.sh; do
 # WARNING: the -i option writes the file
 # so it's better to try first without it
 sed -i 's/port [0-9]\{1,5\}/port 0/g' "$file"
done

vi您可以使用相同的命令:

:s/port [0-9]\{1,5\}/port 0/g

或者更簡單,正如@Quasímodo建議的那樣:

:s/port \d\+/port 0/g

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