从文件读取时在Shell脚本中拆分字符串 [英] Split String in shell script while reading from file

查看:142
本文介绍了从文件读取时在Shell脚本中拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以下脚本,该脚本应从".properties"文件逐行读取,然后在"="分隔符的基础上将其标记化,并将值存储到两个变量中,然后显示它.但是我不了解如何对其进行标记化,然后将其存储在两个不同的变量中,然后将其用于其他目的.

I have a following script which should read line by line from a ".properties" file and then tokenize it on base of "=" delimiter and store values into two variables and then display it. But I am not getting understanding of how to tokenize it and then store it in two different variables and then use it for further purposes.

以下脚本可以很好地逐行读取文件,但我需要帮助实现字符串拆分逻辑.

Following script works fine in reading the file line by line but i need help in implementing the logic of splitting the string.

属性文件"

FNAME=John
LNAME=Lock
DOB=01111989

脚本

#!/bin/bash
echo "FileReading Starts"
while read line
do 
    value=$line
    echo $value
    #Tokenize Logic
    property=sample
    property_value=sample
    echo $property
    echo $property_value
done <testprop.properties

echo "Finish"

推荐答案

尝试一下:

#!/bin/bash

while IFS='=' read -r col1 col2
do 
    echo "$col1"
    echo "$col2"
done <testprop.properties

IFS 是输入文件分隔符.

但是,除了解析文件(如 fedorqui 所述)外,您还可以获取文件并直接访问变量:

But instead of parsing the file (like fedorqui said), you can source the file and accessing the variables directly:

source testprop.properties
echo "$FNAME"

来自 $ LANG = C帮助源:

source: source filename [arguments]
Execute commands from a file in the current shell.

Read and execute commands from FILENAME in the current shell.  The
entries in $PATH are used to find the directory containing FILENAME.
If any ARGUMENTS are supplied, they become the positional parameters
when FILENAME is executed.

Exit Status:
Returns the status of the last command executed in FILENAME; fails if
FILENAME cannot be read.


最后但并非最不重要的是,使用更多引号!参见 http://mywiki.wooledge.org/Quotes http://wiki.bash-hackers.org/syntax/words .

这篇关于从文件读取时在Shell脚本中拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆