本文介绍了读取文件并使用bash程序将每一行分成两个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个程序可以在命令行中读取两个单词:
I have a program that reads two words in command line:
#!/bin/bash
if [[ "$1" != "" && "$2" != "" ]]; then
java -Xmx1024m -cp lib/*:esalib.jar clldsystem.esa.ESAAnalyzer "$1" "$2"
else
java -Xmx1024m -cp lib/*:esalib.jar clldsystem.esa.ESAAnalyzer
fi
我替换了此代码以逐行从文件读取,这是我必须读取的文件的示例:
I replaced this code to read from a file line by line, this is an example of the file that i must read:
vehicle car
computer program
volley ball
代码读取每一行并将每个单词影响到一个变量,问题出在每一行的拆分过程中,因此它会使$ var1和$ var2成为同一个单词
the code read each line and affect each word to a variable, the problem is in the splitting process of each line so it affec to $var1 and $var2 the same word
#!/bin/bash
while read ligne
do
var1=$(echo $ligne | cut -f1 -d-)
var2=$(echo $ligne | cut -f2 -d-)
if [[ "$var1" != "" && "$var2" != "" ]]; then
java -Xmx1024m -cp lib/*:esalib.jar clldsystem.esa.ESAAnalyzer "$var1" "$var2"
else
java -Xmx1024m -cp lib/*:esalib.jar clldsystem.esa.ESAAnalyzer
fi
done < mm.txt
但是新代码没有给出结果
but the new code don't give results
推荐答案
这是调试程序的方式:
#!/bin/bash
while read ligne
do
var1=$(echo $ligne | cut -f1 -d' ')
var2=$(echo $ligne | cut -f2 -d' ')
if [[ "$var1" != "" && "$var2" != "" ]]; then
echo "$var1" '|' "$var2"
#java -Xmx1024m -cp lib/*:esalib.jar clldsystem.esa.ESAAnalyzer "$var1" "$var2"
else
echo "Vars Not Found"
#java -Xmx1024m -cp lib/*:esalib.jar clldsystem.esa.ESAAnalyzer
fi
done < mm.txt
运行此命令将得到以下输出:
Running this gives the following output:
vehicle car | vehicle car
computer program | computer program
volley ball | volley ball
这意味着您的 cut
命令不正确.您可以通过以下几种方法来解决它:
This means that your cut
command is not correct. You have a few options to fix it:
- 如用户3035772所指出的,使用多变量
read
.这不太灵活,因为它依赖于分隔符为$ IFS
,您暗中不同意. - 将
mm.txt
中的定界符固定为-
,作为cut
的-d-
标志命令要求:汽车计算机程序排球
- 修复
cut
命令以要求使用空格分隔符,就像在mm.txt
中一样:cut -f1 -d''
.
- Use multi-variable
read
as user3035772 pointed out. This is less flexible because it relies on the separator being$IFS
, which you are implicitly not agreeing to. - Fix the delimiter in
mm.txt
to be-
as the-d-
flag of thecut
command requires:vehicle-carcomputer-programvolley-ball
- Fix the
cut
command to require a space delimiter as you have inmm.txt
:cut -f1 -d' '
.
这篇关于读取文件并使用bash程序将每一行分成两个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!