aurelien75000
aurelien75000

Reputation: 25

In bash how to echo on the next line into a file?

I try to retrieve the 1st column of the file results and put this column on the file named results2, but the problem is my script only write the last line of results:

for line in $(cat results | cut -d" " -f1);
do echo -e "$line">results2;
done

Upvotes: 0

Views: 54

Answers (1)

Tom Fenech
Tom Fenech

Reputation: 74645

You can do what you want in the shell like this:

while read -r col1 rest
do 
    printf '%s\n' "$col1"
done < results > results2

...but it'd make a lot more sense to just do this:

cut -d' ' -f1 results > results2

The problem with your script is that you're using > inside the loop, which truncates the file and reopens it for writing every iteration. You can get around this by redirecting the whole loop to the file but as I've shown, the best method is just to redirect the output of cut.

To read lines in the shell, use a while read loop; don't read lines with for. However, bear in mind that the shell isn't designed to do this task efficiently, whereas that's exactly what the standard tools such as cut are there for.

Upvotes: 3

Related Questions