Alex
Alex

Reputation: 44305

How to extract text from columns and feed them to a code on Linux (bash)?

Suposing I have the following textfile with spaces, tabs, whatever between those words:

1     test.1
2  word.2
3   whatever.5

I want to extract the second column (does not work with cut -d' ' -f2 test.txt which I cannot understand), then the piece before the decimal point, and feed that result seperately to some code. So the above text file should create three commands:

mycommand test
mycommand word
mycommand whatever

I tried the following construction:

cat test.txt | gawk '{print $2;}' | gawk -F[.] '{print $1;}' | xargs  -0 mycomand

which does not produce the desired result (i.e. creating three distinct jobs).

Questios: 1. How to do it right? 2. How to simplify the expression 3. What is wrong with the cut expression?

Upvotes: 2

Views: 125

Answers (3)

iruvar
iruvar

Reputation: 23364

Drop the -0 argument to . You are feeding newline-separated input to , not NUL-separated. Additionally pass -n 1 to to execute mycommand once per input line. Also, you may combine your invocations to

gawk -F'[[:space:]]+|[.]' '{print $2}'

Upvotes: 2

Jim Garrison
Jim Garrison

Reputation: 86764

Perl answer in case you want another way to do it:

perl -ne'print (((/^\d+\s+([^\.]+)/)[0])."\n")'

Upvotes: 1

$> grep -P -o "(?<= )[^\ \.]+" test.txt | xargs mycommand

Upvotes: 1

Related Questions