Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have a file with lines with IDs, and I'm extracting certain substrings from each line. I've seen this answer, which is great, but I don't know how to get it to execute on each line. I figure xargs should be part of this, but I'm not sure.

As an example, I have this:

123400011234
973700021234
2839900031235
827900041234

(Emboldedned for clarity)

And I want to for each line above to extract this:

0001
0002
0003
0004

Now I know that if one of the lines was $line_one, I could use echo ${line_one: -8:4} to grab the first 4 characters, of the last 8 characters. But I have the lines coming out of the previous command (which is something like cut -d "|" f1, (I think, I'm not at the PC that has the file in question, and that PC doesn't have internet)). What I'm imagining is some world where I can run this:

cut -d "|" -f1 | xargs echo ${xargs_line: -8:4}

To get my output....

Is this possible? If so how?

share|improve this question
add comment

2 Answers

up vote 2 down vote accepted
cut -d "|" -f1 | while read line; do echo ${line: -8:4}; done
share|improve this answer
add comment

You can do the whole thing with just awk:

$ awk -F'|' '{print substr($1,length($1)-7, 4)}' f1

Example

Sample data file f1:

$ cat f1
123400011234|blah|blah
973700021234|blah|blah
2839900031235|blah|blah
827900041234|blah|blah

Running the command produces this:

$ awk -F'|' '{print substr($1,length($1)-7, 4)}' f1
0001
0002
0003
0004
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.