I have a text file called test.txt
that looks like this:
我有一个名为test.txt的文本文件,如下所示:
================
Date = XXXXXX
Path = /path/to/file/
I'm writing a bash script that needs to go into test.txt
and save the directory (not a consistent character length) listed after Path
and save it as a variable to be used later in the bash script. (i.e. save the file path as Dir
and and later in the script be able to call echo $Dir
)
我正在编写一个bash脚本,需要进入test.txt并保存Path后面列出的目录(不是一致的字符长度),并将其保存为稍后在bash脚本中使用的变量。 (即将文件路径保存为Dir,稍后在脚本中可以调用echo $ Dir)
2 个解决方案
#1
Here is one solution:
这是一个解决方案:
Dir=$(sed -ne 's/^Path *= *//p' test.txt)
However many other solutions are possibles
然而,许多其他解决方案是可能的
#2
An awk-based possibility:
基于awk的可能性:
Dir=$(awk '{if ($1 == "Path") print $3}' test.txt)
or, if you want to stay purely within bash built-ins:
或者,如果你想纯粹保持在bash内置插件中:
while read var eq value
do
if [[ $var = Path ]]
then
Dir="$value"
fi
done < test.txt
#1
Here is one solution:
这是一个解决方案:
Dir=$(sed -ne 's/^Path *= *//p' test.txt)
However many other solutions are possibles
然而,许多其他解决方案是可能的
#2
An awk-based possibility:
基于awk的可能性:
Dir=$(awk '{if ($1 == "Path") print $3}' test.txt)
or, if you want to stay purely within bash built-ins:
或者,如果你想纯粹保持在bash内置插件中:
while read var eq value
do
if [[ $var = Path ]]
then
Dir="$value"
fi
done < test.txt