Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic stream/sed? bash script, perform substring on each line

Tags:

bash

sed

I know this is basic, but I couldn't find the simplest way to iterate through a file with hundreds of lines and extract a substring.

If I have a file:

ABCY uuuu
UNUY uuuu

...

I want to end up with:

uuuu
uuuu
....

Ideally do a substring

{5} detect at character 5 and output that

like image 454
Berlin Brown Avatar asked Dec 01 '11 14:12

Berlin Brown


2 Answers

You need no sed:

cut -c5-9 yourfile
like image 131
Michael Krelin - hacker Avatar answered Nov 15 '22 06:11

Michael Krelin - hacker


It would be easier to use cut or awk. Assuming that your fields are separated by a space and you want the second field, you can use:

cut -d' ' -f2 file.txt

awk '{print $2}' file.txt

You can also use cut and awk to extract substrings:

cut -c6- file.txt
awk '{print substr($0,6);}'  file.txt

However, if you really want to iterate through the file and extract substrings, you can use a while loop:

while IFS= read -r line
do
    echo ${line:5}
done < file.txt
like image 21
dogbane Avatar answered Nov 15 '22 06:11

dogbane