extract string between pipes

February 15, 2011 at 23:02:48
Specs: Unix
Hi

I have a file which contains many records each on new line. I need to extract the second and last column values. Columns are seperated by pipe. Can any one please assist?

Appreciate inputs on this from anyone.

Input Format:

0123|4567|1| 22| 40|PQRST

Expected Output:
CONSTANT|4567|PQRST

Here CONSTANT is any fixed string value which I need to insert as the first column in the output.


See More: extract string between pipes

Report •

#1
February 15, 2011 at 23:11:18
A way is to use awk with a Field Seperator of "|" to print the 2nd and the last field to a newdatafile.txt. I choose a space between the columns:

#!/bin/ksh

awk ' BEGIN { FS="|" }
{
printf("CONSTANT|%s|%s\n", $2, $NF)
} ' datafile.txt > newdatafile.txt
# end script

Sorry, I was half asleep when I posted it. Corrected the output.


Report •

#2
February 17, 2011 at 01:07:18
Thanks a lot.

Report •
Related Solutions


Ask Question