bash 从 txt 行读取整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10779133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 02:23:24  来源:igfitidea点击:

read integer from txt line

bashvariablesintegerreadline

提问by jarhead

I have a txt file with 3 lines.

我有一个包含 3 行的 txt 文件。

User$ cat file.txt

用户$猫文件.txt

5 - an integer which needs to be used to determine the end of a loop

5 - 需要用于确定循环结束的整数

1 - a logical which indicates true or false for later conditioning

1 - 一个逻辑,它为以后的条件指示真或假

fold_nam - a name of a folder.

fold_nam - 文件夹的名称。

I now want to assign the 1st line into an integer, what I do so far is:

我现在想将第一行分配给一个整数,到目前为止我所做的是:

echo $(sed -n 1p file.txt) > loop_end

echo $(sed -n 1p file.txt) > loop_end

but when I try to work with the file I cannot get anything

但是当我尝试使用该文件时,我什么也得不到

for example: when I do the following I get a blank line and not the value from the txt file

例如:当我执行以下操作时,我得到一个空行而不是 txt 文件中的值

user$ echo $loop_end

用户$回声$loop_end

I read about this in some forums here and experinment little bit and it does'nt seem the value needs to be converted (BTW, it was saved as an integer though matlab).

我在这里的一些论坛上读到了这个并进行了一些实验,似乎不需要转换该值(顺便说一句,它通过 matlab 保存为整数)。

can use help with the right command line...tnx

可以在正确的命令行中使用帮助...tnx

回答by Prince John Wesley

Assign the output to loop_endvariable of type integer. What you did is redirecting the output to a file named loop_end.

将输出分配给loop_end整数类型的变量。您所做的是将输出重定向到名为loop_end.

declare -i loop_end=$(sed -n 1p file.txt)
echo $loop_end

回答by chepner

Using the readbuilt-in of bash will allow you to read the file contents as in the following example:

使用read内置的 bash 将允许您读取文件内容,如下例所示:

read loop_end < file.txt