首页 > 解决方案 > Cut two fields from a for loop string and use each of them to grep two records from a file

问题描述

The file abc.txt is a line sequential file where each record is having multiple fields. I than want to grep two such fields from another line sequential file zzz.txt and display for comparison.

To do so, I am using a for loop i.e. for i in cat abc.txt. I than want to cut two different fields form the emerging string and want to grep these substrings from a file.

Example script

for i in `cat abc.txt`
do
field1=`cut -c10-15 $i`
field2=`cut -c25-30 $i`
grep $field1 zzz.txt
grep $field2 zzz.txt
done

Problem

When I try doing it the error message shows the string and says that

cut: <string in $i>: No such file or directory

found.

标签: stringgrepshcut

解决方案


错误消息意味着该cut命令尝试将变量的内容$i用作文件名,而这显然不存在。

要使您的脚本正常工作,您需要echo变量内容并将其通过管道传输到cut.

#! /bin/bash

for i in `cat abc.txt`
do

# echo variable content for debugging 
echo "i is ${i}"

field1=$(echo $i | cut -c10-15)
# echo variable content for debugging 
echo "field1 is ${field1}"

field2=$(echo $i | cut -c25-30)
# echo variable content for debugging 
echo "field2 is ${field2}"

grep ${field1} zzz.txt
grep ${field2} zzz.txt
done

还请查看bash 脚本在变量处使用剪切命令并将结果存储在另一个变量或其他类似问题。


推荐阅读