gpt4 book ai didi

linux - 使用 bash 根据其他文件中的范围划分文件

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

我在 linux 中有一个文件:

文件有数字范围,文件是这样的:

100,500
501,1000
1001,2000

我还有其他包含单词和数字的文件:

a,105
b,110
c,550
d,670
e,900
f,80
h,1500

然后我需要过滤文件并根据第一个文件中的范围生成文件。然后我需要 3 个文件:

<<110,500>>
a,105
b,110

<<501,1000>>
c,550
d,670
e,900

<<1001,2000>>
h,1500

使用 bash 脚本

我可以像这样读取第一个文件:

while read line
do
init=`echo $line | awk 'BEGIN {FS=","}{print $1}'`
end=`echo $line | awk 'BEGIN {FS=","}{print $2}'`
done <rangos.txt

我有范围,但我不知道如何根据第一个文件的范围划分第二个文件。

谁能帮帮我?

谢谢

最佳答案

这里是 bash 中的示例解析器:

#!/bin/bash

declare file1=file1
declare file2=file2
while read line; do
if [ -z "${line}" ]; then continue; fi # empty lines
declare -i left=${line%%,*}
declare -i right=${line##*,}

echo "<<$left,$right>>"

OIFS=$IFS
IFS=' '
for word in $(<$file2); do
declare letter=${word%%,*}
declare -i value=${word##*,}

if [[ $left -le $value && $value -le $right ]]; then
echo "$letter,$value"
fi
done
IFS=$OIFS
done < "${file1}"

在 Debian Wheezy 下用 bash4 测试,它打印:

$ ./parser.sh 
<<100,500>>
a,105
b,110
<<501,1000>>
c,550
d,670
e,900
<<1001,2000>>
h,1500

但是,根据您对 perl 或其他语言的评论,您应该使用您或您的团队更熟悉的语言来完成。

关于linux - 使用 bash 根据其他文件中的范围划分文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25449378/

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