Chr*_*one 5 sed awk aix text-processing
我正在运行 AIX 5.3(不是故意的,但我无法更改它),并且我有一个文本文件:servers.txt 下面是文件内容的示例:
apple port1 username password IPAddress TCP
banana port2 username password IPAddress TCP
beet port3 username password IPAddress TCP
apple port4 username password IPAddress TCP
avocado port1 username password IPAddress TCP
tomato port2 username password IPAddress TCP
avocado port3 username password IPAddress TCP
peach port4 username password IPAddress TCP
avocado port5 username password IPAddress TCP
avocado port6 username password IPAddress TCP
strawberry port1 username password IPAddress TCP
strawberry port2 username password IPAddress TCP
strawberry port3 username password IPAddress TCP
avocado port1 username password IPAddress TCP
lemon port2 username password IPAddress TCP
strawberry port3 username password IPAddress TCP
avocado port4 username password IPAddress TCP
Run Code Online (Sandbox Code Playgroud)
我有一个列表文件:newservers.lst,其中包含四个服务器名称的列表:
beet
banana
cherry
tomato
Run Code Online (Sandbox Code Playgroud)
我需要遍历“servers.txt”,然后用“newservers.lst”中的名称依次替换服务器名称“avocado”的所有实例。
这是我需要结束的事情:
apple port1 username password IPAddress TCP
banana port2 username password IPAddress TCP
beet port3 username password IPAddress TCP
apple port4 username password IPAddress TCP
beet port1 username password IPAddress TCP
tomato port2 username password IPAddress TCP
banana port3 username password IPAddress TCP
peach port4 username password IPAddress TCP
cherry port5 username password IPAddress TCP
tomato port6 username password IPAddress TCP
strawberry port1 username password IPAddress TCP
strawberry port2 username password IPAddress TCP
strawberry port3 username password IPAddress TCP
beet port1 username password IPAddress TCP
lemon port2 username password IPAddress TCP
strawberry port3 username password IPAddress TCP
banana port4 username password IPAddress TCP
Run Code Online (Sandbox Code Playgroud)
有没有办法用 sed 命令来完成这个,还是我需要使用 do/while 循环或类似的?
试试awk
awk '
NR==FNR{
A[NR]=$1
limit=NR
next
}
/^avocado/{
i=i%limit+1
$1=A[i]
}
{
print
}
' newservers.lst servers.txt
Run Code Online (Sandbox Code Playgroud)
Sed也是可能的:
sed '/^\s*\S\+\s*$/ { #match 1st file only
x #exchange line with holdspace
H #add pre-holdspace to pre-line
d #no print
} #result: reversed 1st file in holdspace
/^avocado/{
G #add holdspace to line
s/\S\+\(.*\)\n\(\w\+\)\n*$/\2\1/
#replace 1st word by last word(from holdspace)
P #print line before holdspace resedue
s/\s[^\n]*// #remove all from 1st word to holdspace
h #return holdspace with last word became first
d #no print
}
' newservers.lst servers.txt
Run Code Online (Sandbox Code Playgroud)