4

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

user3304726
  • 219
  • 2
  • 4
  • 17

1 Answers1

22

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.

konsolebox
  • 72,135
  • 12
  • 99
  • 105