Use a word as a delimiter for cut command in linux without using awk

Viewed 1955

I'm trying to take the second segment of a line inside a file delimited by a certain string, and it would usually work something like awk -F ':: My Delimiter ::' '{print $2}', but if I try to print $2 it will print the second argument passed onto the function in which the awk command is located. Is there an alternate way to split a line by a delimiter and print a certain part of the result?

This is the exact line I'm having issues with:

for transaction in $(cat $1)
do
    echo "$transaction" | awk -F ':: My Delimiter ::' '{print $2}' >> testLog.data.out
done

Note: The delimiter would be exactly as described. :: My Delimiter ::

2 Answers

Rather than using cut, I think you should really use awk - your example awk -F ':: My Delimiter ::' '{print $2}' should work. If you printed the second arguments passed into the function containing that awk, then that means the $2 was not inside single quotes - maybe you used double quotes? This wouldn't work (notice the double quotes):

awk -F ':: My Delimiter ::' "{print $2}"

But this would (your example):

awk -F ':: My Delimiter ::' '{print $2}'

You can use this code:

echo ':: My Delimiter ::' | awk '{split($0,v,"My Delimiter"); print v[2]}' 


>>> echo 'ThisIsINeed0 My Delimiter ThisIsINeed1' | awk '{split($0,v," My Delimiter "); print v[1]}'
ThisIsINeed0
>>> echo 'ThisIsINeed0 My Delimiter ThisIsINeed1' | awk '{split($0,v," My Delimiter "); print v[2]}' 
ThisIsINeed1


>>> echo 'This Is I Need 0 My Delimiter This Is I Need 1' | awk '{split($0,v," My Delimiter "); print v[2]}' 
This Is I Need 1
>>> echo 'This Is I Need 0 My Delimiter This Is I Need 1' | awk '{split($0,v," My Delimiter "); print v[1]}' 
This Is I Need 0
Related