Wim De Troyer
Wim De Troyer

Reputation: 492

using xargs as an argument for cut

Say i have a file a.txt containing a word, followed by a number, followed by a newline on

and 3
now 2
for 2
something 7
completely 8
different 6

I need to select the nth char from every word (specified by the number next to the word)

cat a.txt | cut -d' ' -f2 | xargs -i -n1 cut a.txt -c {}

I tried this command, which selects the numbers and uses xargs to put them into the -c option from cut, but the cut command gets executed on every line, instead of a.txt being looped (which I had expected to happen) How can I resolve this problem?

EDIT: Since it seems to be unclear, i want to select a character from a word. The character which I need to select can be found next to the word, for example: and 3, will give me d. I want to do this for the entire file, which will then form a word :)

Upvotes: 5

Views: 8101

Answers (2)

terdon
terdon

Reputation: 3370

A pure shell solution:

$ while read word num; do echo ${word:$((num-1)):1}; done < a.txt 
d
o
o
i
e
r

This is using a classic while; do ... ; done shell loop and the read builtin. The general format is

while read variable1 variable2 ... variableN; do something; done < input_file

This will iterate over each line of your input file splitting it into as many variables as you've given. By default, it will split at whitespace but you can change that by changing the $IFS variable. If you give a single variable, the entire line will be saved, if you give more, it will populate as many variables as you give it and save the rest in the last one.

In this particular loop, we're reading the word into $word and the number into $num. Once we have the word, we can use the shell's string manipulation capabilities to extract a substring. The general format is

${string:start:length}

So, ${string:0:2} would extract the first two characters from the variable $string. Here, the variable is $word, the start is the number minus one (this starts counting at 0) and the length is one. The result is the single letter at the position given by the number.

Upvotes: 2

Tom Fenech
Tom Fenech

Reputation: 74595

I would suggest that you used awk:

awk '{print substr($1,$2,1)}' file

substr takes a substring of the first field starting from the number contained in the second field and of length 1.

Testing it out (using the original input from your question):

$ cat file
and 3
now 2
for 2
something 7
completely 8
different 6
$ awk '{print substr($1,$2,1)}' file
d
o
o
i
e
r

Upvotes: 1

Related Questions