• Skip to main content

Uly.me

cloud engineer

  • Home
  • About
  • Archives

loop

Bash Read File

December 1, 2021

How to read a file line by line in Bash.

#!/bin/bash
file=test.txt
while IFS= read -r line; do
  echo $line
done < $file

#!/bin/bash file=test.txt while IFS= read -r line; do echo $line done < $file

Contents of test.txt.

one
two
three

one two three

Results when running test.sh.

$ bash test.sh
one
two
three

$ bash test.sh one two three

To read multiple strings line by line.

#!/bin/bash
file=test.txt
while read -r a b; do
  echo $b
done < $file

#!/bin/bash file=test.txt while read -r a b; do echo $b done < $file

Modified contents of test.txt.

one 1
two 2
three 3

one 1 two 2 three 3

New results.

$ bash test.sh
1
2
3

$ bash test.sh 1 2 3

Filed Under: Linux Tagged With: bash, file, loop, output, read

Remove Last Comma In Loop

December 26, 2012

When performing a database query, we normally use a loop to output the database result. This is a common exercise for programmers when displaying results to the screen. To make the output readable, commas are typically used to separate data. Consider a loop below that prints a list of names. We added a string ‘, ‘ after each name to make it readable.

foreach($query as $item) :
echo $item->name.', '; 
endforeach;

foreach($query as $item) : echo $item->name.', '; endforeach;

The output would be something like this:
John, Mary, Steve, Mark,

The output works as intended, but there is a trailing comma at the end that we don’t want. We either need to get rid of it, or replace it with a period. So, how do we do that? Here’s how.

We will use the trim() function to remove the last comma. But before we can do that, we should probably hold off on echoing to the screen until the loop is finished. So, we will store the results in a variable called $result as we go through the loop. To avoid a PHP undefined variable error, we need to initialize the $result variable before the loop begins. After the loop, we will use the rtrim function to remove the last comma. Finally, we echo the trimmed results and add a period.

$result="";
foreach($query as $item) :
$result.=$item->name.', '; 
endforeach;
$trimmed=rtrim($result, ', ');
echo $trimmed;
echo '.';

$result=""; foreach($query as $item) : $result.=$item->name.', '; endforeach; $trimmed=rtrim($result, ', '); echo $trimmed; echo '.';

The output is now:
John, Mary, Steve, Mark.

Filed Under: PHP Tagged With: commas, loop

  • Home
  • About
  • Archives

Copyright © 2023