user3304726
user3304726

Reputation: 259

removing linebreak from a line read from a file in bash

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

Upvotes: 4

Views: 13485

Answers (1)

konsolebox
konsolebox

Reputation: 75458

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.

Upvotes: 22

Related Questions