LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   bash: read from character x to y for every line (https://www.linuxquestions.org/questions/programming-9/bash-read-from-character-x-to-y-for-every-line-4175713525/)

vanKey 06-17-2022 01:30 AM

bash: read from character x to y for every line
 
Hello all,

for the file test.dat, I want to extract the characters at position 7,8 and 9 of each line.
It is important to exactly specify the range from 7 to 9. I can't use $4 to pick it via awk.

content of file test.dat:
Code:

1 2 3 456 789
1 3 4 789 101112

this is how it should like afterwards
Code:

456
789

Has anyone an idea?

Kind regards
vanKey

chrism01 06-17-2022 01:35 AM

You mean like this ?
Code:

echo '1 2 3 456 789'|cut -c7,8,9
456


Turbocapitalist 06-17-2022 01:35 AM

Yes, either AWK or Perl will do that quite easily. Please post what you have tried and where you are stuck. Be sure to use [code] [/code] tags around your work to preserve indentation.

vanKey 06-17-2022 01:42 AM

What I did is

Code:

awk '{print $4}' test.dat
But I have a far more complex file than this and this is only a minimum example.
What I need is to specify something in awk with reference to the line entry ID's 7-9, that have to be put out.

Kind regards
vanKey

Turbocapitalist 06-17-2022 01:46 AM

Quote:

Originally Posted by vanKey (Post 6361577)
But I have a far more complex file than this and this is only a minimum example.

Thanks. Please provide a more complete example.

Check the various guides periodically as you get closer to your goal. Bruce Barnett's AWK tutorial is quite a good one for that.

ArfaSmif 06-17-2022 01:59 AM

If you always want positions 7-9 then all you need is

cut -c7-9 test.dat >> output-file.dat

syg00 06-17-2022 03:32 AM

I seem to recall advising you to download and read the gawk doco at the link I provided. Do so.

vanKey 06-17-2022 04:23 AM

Thanks ArfaSmif, that did it!

Kind regards

ondoho 06-18-2022 12:17 AM

Why not pure bash, as the thread title suggests?
Code:

while read line; do
    echo "${line:6:3}"
done <file


MadeInGermany 06-19-2022 04:28 AM

Note that the read command defaults to some magic:
skipping initial space, special treatment of backslash.
You can turn the magic off with
Code:

while IFS= read -r line; do

teckk 06-19-2022 10:34 AM

Code:

txt="
1 2 3 456 789
1 3 4 789 101112
a b c sde 12wsd4
3 4 5 67890 33 555
"

while read line; do
    echo "${line:6:3}"
done <<< "$txt"

456
789
sde
678

Bash does not cease to be nifty. No matter how many times you do it.


All times are GMT -5. The time now is 04:23 PM.