gpt4 book ai didi

linux - 使用 bash 从文本文件中提取单词

转载 作者:太空宇宙 更新时间:2023-11-04 05:36:44 24 4
gpt4 key购买 nike

我有一个类似于下面的文本文件:

text src=127.0.0.1 text dst=127.0.0.1 text text proto=23
text text text src=192.168.1.254 text text dst=192.168.1.40 text proto=3389
text src=10.213.18.254 text dst=192.168.15.3 text text proto=389
text text text src=192.168.1.254 text text dst=192.168.1.40 text proto=3389
...

我想要一个与此类似的输出文件(使用 bash):

src=127.0.0.1 dst=127.0.0.1 proto=23
src=192.168.1.254 dst=192.168.1.40 proto=3389
src=10.213.18.254 dst=192.168.15.3 proto=389
src=192.168.1.254 dst=192.168.1.40 proto=3389

不幸的是,信息并不总是在同一列上(这使得 awk 毫无用处)。 bash 有办法执行此操作吗?

最佳答案

在纯 bash 中:

#!/bin/bash

# read each line into an array of words
while read -r -a words_in; do

# copy only words containing '=' into an output array
words_out=()
for word in "${words_in[@]}"; do
[[ $word = *=* ]] && words_out+=( "$word" )
done

# use first character of $IFS to join contents of output array when printing.
printf '%s\n' "${words_out[*]}"
done

如果您想要不同的标准,修改内部循环的内容应该很简单。例如,仅传递以 src=dst=proto= 开头的单词:

  for word in "${words_in[@]}"; do
case $word in
src=*|dst=*|proto=*) words_out+=( "$word" ) ;;
esac
done

关于linux - 使用 bash 从文本文件中提取单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22182604/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com