Reputation: 141
Suppose I have file with a single line.
/a/n/v//9.3/b/ld --verbose -o o/c/f/r1 -r o/c/f/fn.o o/c/f/fyt.o L/fs/ed/pl/tls/oe -L/apps/ose/5.5.3//lib/powerpc -lc -lrt -lm -lcp -lel -lip -lubs -lpp -lpc /a/oe/5.3//g3/l/g.3/nf/libgcov.a -lrds -l00_ex -lmcu /a/n/v//9.3/b/ld --verbose -o o/ce/wef/r34
I want to search for the pattern starting with "-l" and arrange it in the below order in another file.
-lc
-lrt
-lm
-lcp
-lel
-lip
-lubs
-lpp
-lpc
-lrds
-l00_ex
-lmcu
What command could be used to search the pattern mentioned above?
Upvotes: 1
Views: 172
Reputation: 37258
Here you go:
echo "/a/n/v//9.3/b/ld --verbose -o o/c/f/r1 -r o/c/f/fn.o o/c/f/fyt.o L/fs/ed/pl/tls/oe -L/apps/ose/5.5.3//lib/powerpc -lc -lrt -lm -lcp -lel -lip -lubs -lpp -lpc /a/oe/5.3//g3/l/g.3/nf/libgcov.a -lrds -l00_ex -lmcu /a/n/v//9.3/b/ld --verbose -o o/ce/wef/r34" \
| awk '{for (i=1;i<=NF;i++) {if ($i ~ /^-l/) print $i }}' | sort
output
-l00_ex
-lc
-lcp
-lel
-lip
-lm
-lmcu
-lpc
-lpp
-lrds
-lrt
-lubs
Needless to say, if you don't want the output sorted for some reason, just remove |sort
on the end. It will then print the arguments in the order listed on the cmd-line. (I suppose sometimes that would be important).
I'm using a standard awk idom, of iterating per element over the provided input
for (i=1;i<=NF;i++)
the i
is a tmp variable, NF
means N umber (of) F ields, meaning the num-of-fields in the current line. The test is done with regular expression test
if ($i ~ /^-l/ )
where $i
is the value of the i'th position in the input, and ^
indicates "must be at the front of the string", while -l
matches any of the inputs you have provided.
echo
ing your data to awk
via a pipe shows that awk
is very comfortable reading from std-in, so you can replace echo
with grep yourSearchtarget yourFile | awk ...
or any other command that will return the lines you need for processing.
IHTH
Upvotes: 1