为行分配变量名Unix

时间:2014-08-31 04:26:37

标签: bash shell unix grep

我目前正在读取unix中三个字母字符串的文件,并想知道如何制作行变量以便我可以在代码中使用它们...

我的想法是这样的:

!#/bin/bash

IFS=''
while read line
  do
    code=$(line) 
    #This would be where I want to assign the line a variable
    grep "$code" final.txt >  deptandcourse.txt 
    #This is where I would want to grep according to that three letter string
done < strings.txt

示例文件(strings.txt):

ABC
BCA
BDC

我想把这些字母放在变量行中,然后先将文件(final.txt)grep为'ABC',然后'BCA',然后'BDC'

1 个答案:

答案 0 :(得分:0)

line是一个变量,您已将其设置为包含您在整个循环中读取的文件的每一行的内容,因此您无需将其重新分配给另一个变量。有关在循环中使用read的详细信息,请参阅this page

此外,您可能希望将deptandcourse.txt附加到>>,因为使用>重定向会每次都覆盖该文件。

也许这就是你想要的:

while read -r line
  do 
    grep "$line" final.txt >> deptandcourse.txt 
done < strings.txt

@JohnZwinck 在评论中提出:

grep -f strings.txt final.txt > deptandcourse.txt

这似乎是最好的解决方案。

你也可以使用awk来完成同样的事情:

awk 'FNR==NR {
    a[$0]
    next
}
{
    for(i in a)
        if($0 ~ i)
             print
}' strings.txt final.txt > deptandcourse.txt
相关问题