Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removing linebreak from a line read from a file in bash

Tags:

bash

shell

I have a file containing some lines. I wanted to store each line to a variable , but the line must be chomped (the way its done in perl - chomp($Line) ) in shell script.

The code containing the functionality of opening a file and reading the lines is

p_file() {

File=$1
count=0

while read LINE
do
      chomped_line=$LINE    **#How to delete the linebreaks** 
      echo $chomped_line

done < $File

}

How to delete the linebreaks and store the string in the variable(chomped_line) as above

like image 360
user3304726 Avatar asked Dec 02 '22 16:12

user3304726


1 Answers

Simply use

while IFS=$' \t\r\n' read -r line

It would exclude leading and trailing spaces even carriage returns characters (\r) every line. No need to chomp it.

If you still want to include other spaces besides \n and/or \r, just don't specify the others:

while IFS=$'\r\n' read -r line

Another way if you don't like using IFS is just to trim out \r:

chomped_line=${line%$'\r'}

  *  -r prevents backslashes to escape any characters.

like image 152
konsolebox Avatar answered Dec 29 '22 01:12

konsolebox