S
S
s_pyanov2015-11-19 16:46:32
linux
s_pyanov, 2015-11-19 16:46:32

Bash: while read line + sed. How to assign different parts of string to 2 variables?

Good day to all.
I have a task:
there is an incoming file, it consists of lines of this kind.
host-ivan,10.70.0.1 #Хост Иванова
host-petr,10.70.0.2 #Хост Петрова
host-sid,10.70.0.3 #Хост Сидорова
The task is to write a function that will read this file, enters the part of the line up to the 'comma' into the X variable, and the IP address from the same line will be entered into the Y variable. That x=host-ivan y=10.70.0.1
is, I try to do it through while

while read line
do
        x=$(sed -r 's/,.+//')                    #Вырезаем первую часть строки до запятой
        y=$(sed 's|.*,||' | sed -r 's/#.+//')    #Вырезаем кусок от запятой до # (IP адрес)
        echo "$x$y" \
done <list

When executing, I get only the result of the execution, the x=$(sed -r 's/,.+//')line is y=$(sed 's|.*,||' | sed -r 's/#.+//')ignored, if I comment X, then the line with Y is processed.
It turns out that the first line in the cycle CUTs everything out of the line and for Y there is an empty line?
I do not fully understand what exactly happens to the line value at each stage of execution, can anyone tell me how to implement my function?
Maybe while is not suitable for this? Or sed?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
3
3vi1_0n3, 2015-11-19
@s_pyanov

No need for sed. On a clean tower:

#!/bin/bash

IFS='
'
(
while read line
do
    line=${line%% *}
    x=${line%,*}
    y=${line##*,}
    echo $x
    echo $y
done
) < file.txt

S
S_SN, 2015-11-19
@S_SN

And who's stopping you from taking not "line", but any variable
and working with it as you like

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question