data:
hello--hello1--hello2--#growncars#vello--hello3--hello4--jello#growncars#dello--gello--gelloA--gelloB#growncars#
I want to be able to print all the values that are found between the patterns "#growncars #" and the next "#growncars #" on the same line.
so the output should be:
vello--hello3--hello4--jello
dello--gello--gelloA--gelloB
The actual data will be much larger than what I provided above. but the goal is the same. i need to grab only the fields that are between that patterns.
i would like to use awk for this and hopefully it'll be a solution that is portable.
Hello SkySmart,
Could you please try following and let me know if this helps you.
awk '{match($0,/#growncars#.*#growncars#/);VAL=substr($0,RSTART,RLENGTH);gsub(/^#growncars#|#growncars#$/,X,VAL);gsub(/#growncars#/,"\n",VAL);print VAL}' Input_file
Thanks,
R. Singh
1 Like
Hi,
In sed:
echo "xy--#growncars#vello--hello3--hello4--jello#growncars#dello--gello--gelloA--gelloB#growncars#" | sed -e 's/.*#growncars#\(.*\)#growncars#\(.*\)#growncars#/\1\n\2/'
Gives the output:
vello--hello3--hello4--jello
dello--gello--gelloA--gelloB
2 Likes
RudiC
January 3, 2017, 1:16pm
4
Why the scenic route with VAL?
awk '{gsub (/#growncars#/, "\n"); sub ("^[^\n]*\n", ""); sub ("\n[^\n]*$", "")} 1' file
vello--hello3--hello4--jello
dello--gello--gelloA--gelloB
EDIT:
Or sed
:
sed 's/#growncars#/\n/g; s/^[^\n]*\n\|\n[^\n]*$//g' file
2 Likes
Try, works with current data
akshay@db-3325:/tmp$ cat f
hello--hello1--hello2--#growncars#vello--hello3--hello4--jello#growncars#dello--gello--gelloA--gelloB#growncars#
akshay@db-3325:/tmp$ awk '$0==p{s=1;next}s && NF; $0==p{s=0}' RS="#" p="growncars" f
vello--hello3--hello4--jello
dello--gello--gelloA--gelloB
1 Like
Hello SkySmart,
Could you please try following also once and let me know if this helps, with sample Input_file it is working fine.
awk -F"#growncars#" '{for(i=2;i<=NF-1;i++){if($i){print $i}}}' Input_file
Thanks,
R. Singh
1 Like
looney
January 4, 2017, 1:05pm
7
Hello RudiC, could you please explain below highlighted part of code. sed
:
sed 's/#growncars#/\n/g; s/^[^\n]*\n\|\n[^\n]*$//g' file
.
RudiC
January 4, 2017, 5:03pm
8
Love to:
s/ # substitute regex
^[^\n]*\n # 0 or more non- <NL> chars (anchored at BOL) followed by a <NL>
\| # OR
\n[^\n]*$ # a <NL> followed by 0 or more non- <NL> chars anchored at EOL
// # empty replacement (= delete regex matches)
g # the substitute is needed twice: one for BOL, one for EOL
I would have suggested a slightly simplified version of RavinderSingh13's 2nd suggestion (from post #6 ):
awk -F'#growncars#' '{for(i = 2; i < NF; i++) print $i}' Input_file