2

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?

2
cut -d "|" -f1 | while read line; do echo ${line: -8:4}; done
3

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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