string - 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.
解决方案
错误消息意味着该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 脚本在变量处使用剪切命令并将结果存储在另一个变量或其他类似问题。
推荐阅读
- merge - Jsonnet 中的 + 运算符和 std.mergePatch 有什么区别?
- c - 'g' 在此函数中使用未初始化 [-Wuninitialized]
- python - 如何在我们绘制列表平均值并显示其余范围的列表中绘制键的字典? [Python]
- python - 更快的 datetime.strptime
- php - Magento 2 搜索显示 404 Not Found
- jquery - JQuery 文本搜索:无法获得正确的标签/元素来搜索表格文本
- azure-service-fabric - Service Fabric - 如何在我的本地开发集群上启用 BackupRestoreService
- bluetooth - BLE 设备中可能的连接数
- .net-core - 使用 Microsoft Graph SDK 列出我组织中所有组的计划
- css - 为什么我的 VS code live sass 编译器编译单独的 css 文件?