Skip to main content

Linux Shell: Extract values separated by pipes from a file [Resolved]

I have the following values in a file:

line 1: 31915
line 2: Salchipapa|papa|salchicha|aceite|queso

I need to get the values papa, salchicha, aceite, queso

that means that i have to get the values from the line 2, column 2 On.


Question Credit: user357018
Question Reference
Asked June 17, 2019
Tags: linux, shell
Posted Under: Unix Linux
31 views
4 Answers

I did it like this and it worked:

     for i in {2..10}
     do
        ingName=$(sed -n 2p $filename | cut -d '|' -f $i)
     done

"sed -n 2p $filename" gets the second line of the file and then "cut -d '|' -f $i" gives me each ingredient separated by pipes. the number 10 indicates that there are maximum 10 ingredients, so later on in the code I validate that I worked only when the variable ingName is not null.


credit: user357018
Answered June 17, 2019

Tried with below command and it worked fine

awk 'NR==2{print $NF}' filename| awk -F "|" '{$1="";print $0}' |sed -r "s/^\s+//g"| perl -pne "s/ /\n/g"

output

papa
salchicha
aceite
queso

credit: Praveen Kumar BS
Answered June 17, 2019
Your Answer
D:\Adnan\Candoerz\CandoProject\vQA