0

I am looking to extract 2 names from a pipe delimited file which looks like below,

1|1234|first name|2|56768|second      name   |message

my code looks like below,

cat $file_name|while read row; do
name1=`echo $row | awk -F\| '{ print $3 }'`
name2=`echo $row | awk -F\| '{ print $6 }'`
echo name1 is $name1
echo name2 is $name2

The problem I am facing is above code is removing multiple spaces within the actual data and also removing trailing spaces.

I need to have data as it is e.g. it should keep multiple spaces within data if original data has multiple spaces within it.

can anyone please suggest how can I extract name1 and name2 as above preserving spaces in the data ?

if reading fields by while loop or by awk is not good method then can you please suggest alternative way or perl script way instead of bash ??

gumbol
  • 9
  • 1
  • I am not sure why multiple spaces are not showing up here but my data has multiple spaces within it e.g. "second name " – gumbol Jun 06 '18 at 11:07
  • Too see the spaces you need to quote the shell variable in your echo statement: `echo name1 is "$name1"`. – jas Jun 06 '18 at 11:11
  • If you let us know what you're trying to do at a higher level it almost certainly can be done much more efficiently with a single invocation of awk and no looping in the shell. – jas Jun 06 '18 at 11:14
  • Thanks. here I have shown echo statement just to demonstrate my issue, in reality I am not echoing that name1 variable but using "$name1" to do further processing like greping that name and processing etc. but things are not working when there are spaces within data. – gumbol Jun 06 '18 at 11:14
  • jas, my file has 10k records so I need to get the names out of it and do some processing by looking into other files. So I need exact data to search into other file due to this I want data as original (with spaces in it (if it has spaces) – gumbol Jun 06 '18 at 11:18
  • You also need the quotes around `$row`: `echo "$row" | ...` – jas Jun 06 '18 at 11:19

0 Answers0